Chore: Improve some types (#64675)

* some type fixes

* few more

* more type fixes

* fix the majority of (window as any) calls

* don't make new variable for event

* few more

* MOAR
This commit is contained in:
Ashley Harrison
2023-03-14 09:51:44 +00:00
committed by GitHub
parent aade4b0bd2
commit 53186c14a4
73 changed files with 256 additions and 436 deletions

View File

@@ -640,7 +640,7 @@ describe('getLinksSupplier', () => {
},
],
},
display: (v) => ({ numeric: v, text: String(v) }),
display: (v) => ({ numeric: Number(v), text: String(v) }),
},
],
});

View File

@@ -1,6 +1,6 @@
import { FormattedValue } from '../valueFormats';
export type DisplayProcessor = (value: any, decimals?: DecimalCount) => DisplayValue;
export type DisplayProcessor = (value: unknown, decimals?: DecimalCount) => DisplayValue;
export interface DisplayValue extends FormattedValue {
/**

View File

@@ -87,10 +87,10 @@ export class Registry<T extends RegistryItem> {
this.initialize();
}
const select = {
const select: RegistrySelectInfo = {
options: [],
current: [],
} as RegistrySelectInfo;
};
const currentOptions: Record<string, SelectableValue<string>> = {};
if (current) {

View File

@@ -34,7 +34,7 @@ export interface CSVParseCallbacks {
onHeader: (fields: Field[]) => void;
// Called after each row is read
onRow: (row: any[]) => void;
onRow: (row: string[]) => void;
}
export interface CSVOptions {
@@ -73,9 +73,9 @@ export class CSVReader {
}
// PapaParse callback on each line
private chunk = (results: ParseResult<any>, parser: Parser): void => {
private chunk = (results: ParseResult<string[]>, parser: Parser): void => {
for (let i = 0; i < results.data.length; i++) {
const line: string[] = results.data[i];
const line = results.data[i];
if (line.length < 1) {
continue;
}
@@ -191,15 +191,18 @@ export class CSVReader {
}
}
type FieldWriter = (value: any) => string;
type FieldWriter = (value: unknown) => string;
function writeValue(value: any, config: CSVConfig): string {
function writeValue(value: unknown, config: CSVConfig): string {
if (value === null || value === undefined) {
return '';
}
const str = value.toString();
if (str.includes('"')) {
// Escape the double quote characters
return config.quoteChar + str.replace(/"/gi, '""') + config.quoteChar;
}
if (str.includes('\n') || str.includes(config.delimiter)) {
if (str.includes('\n') || (config.delimiter && str.includes(config.delimiter))) {
return config.quoteChar + str + config.quoteChar;
}
return str;
@@ -207,13 +210,13 @@ function writeValue(value: any, config: CSVConfig): string {
function makeFieldWriter(field: Field, config: CSVConfig): FieldWriter {
if (field.display) {
return (value: any) => {
return (value: unknown) => {
const displayValue = field.display!(value);
return writeValue(formattedValueToString(displayValue), config);
};
}
return (value: any) => writeValue(value, config);
return (value: unknown) => writeValue(value, config);
}
function getHeaderLine(key: string, fields: Field[], config: CSVConfig): string {
@@ -229,7 +232,7 @@ function getHeaderLine(key: string, fields: Field[], config: CSVConfig): string
line = line + config.delimiter;
}
let v: any = fields[i].name;
let v = fields[i].name;
if (isType) {
v = fields[i].type;
} else if (isName) {

View File

@@ -1,7 +1,7 @@
import { guessFieldTypeFromValue } from '../dataframe/processDataFrame';
import { Field, FieldType } from '../types/dataFrame';
export function makeFieldParser(value: any, field: Field): (value: string) => any {
export function makeFieldParser(value: unknown, field: Field): (value: string) => any {
if (!field.type) {
if (field.name === 'time' || field.name === 'Time') {
field.type = FieldType.time;

View File

@@ -23,14 +23,11 @@ export function parseLabels(labels: string): Labels {
* Returns a map labels that are common to the given label sets.
*/
export function findCommonLabels(labelsSets: Labels[]): Labels {
return labelsSets.reduce((acc, labels) => {
if (!labels) {
throw new Error('Need parsed labels to find common labels.');
}
if (!acc) {
// Initial set
acc = { ...labels };
} else {
return labelsSets.reduce(
(acc, labels) => {
if (!labels) {
throw new Error('Need parsed labels to find common labels.');
}
// Remove incoming labels that are missing or not matching in value
Object.keys(labels).forEach((key) => {
if (acc[key] === undefined || acc[key] !== labels[key]) {
@@ -43,9 +40,10 @@ export function findCommonLabels(labelsSets: Labels[]): Labels {
delete acc[key];
}
});
}
return acc;
}, undefined as unknown as Labels);
return acc;
},
{ ...labelsSets[0] }
);
}
/**

View File

@@ -30,7 +30,7 @@ export function getLogLevel(line: string): LogLevel {
if (result) {
if (currentIndex === undefined || result.index < currentIndex) {
level = (LogLevel as any)[key];
level = LogLevel[key as keyof typeof LogLevel];
currentIndex = result.index;
}
}
@@ -40,7 +40,7 @@ export function getLogLevel(line: string): LogLevel {
/** @deprecated will be removed in the next major version */
export function getLogLevelFromKey(key: string | number): LogLevel {
const level = (LogLevel as any)[key.toString().toLowerCase()];
const level = LogLevel[key.toString().toLowerCase() as keyof typeof LogLevel];
if (level) {
return level;
}
@@ -136,7 +136,7 @@ export function calculateLogsLabelStats(rows: LogRowModel[], label: string): Log
const rowCount = rowsWithLabel.length;
// Get label value counts for eligible rows
const countsByValue = countBy(rowsWithLabel, (row) => (row as LogRowModel).labels[label]);
const countsByValue = countBy(rowsWithLabel, (row) => row.labels[label]);
return getSortedCounts(countsByValue, rowCount);
}

View File

@@ -2,8 +2,10 @@
* @beta
* Proxies a ES6 class so that it can be used as a base class for an ES5 class
*/
export function makeClassES5Compatible<T>(ES6Class: T): T {
return new Proxy(ES6Class as any, {
export function makeClassES5Compatible<T extends abstract new (...args: ConstructorParameters<T>) => InstanceType<T>>(
ES6Class: T
): T {
return new Proxy(ES6Class, {
// ES5 code will call it like a function using super
apply(target, self, argumentsList) {
if (typeof Reflect === 'undefined' || !Reflect.construct) {
@@ -12,5 +14,5 @@ export function makeClassES5Compatible<T>(ES6Class: T): T {
return Reflect.construct(target, argumentsList, self.constructor);
},
}) as unknown as T;
});
}

View File

@@ -1,7 +1,7 @@
import { standardTransformersRegistry } from '../../transformations';
import { DataTransformerInfo } from '../../types';
export const mockTransformationsRegistry = (transformers: Array<DataTransformerInfo<any>>) => {
export const mockTransformationsRegistry = (transformers: DataTransformerInfo[]) => {
standardTransformersRegistry.setInit(() => {
return transformers.map((t) => {
return {

View File

@@ -42,5 +42,5 @@ export function sci(value: number | null, decimals: DecimalCount): FormattedValu
if (value == null) {
return { text: '' };
}
return { text: value.toExponential(decimals as number) };
return { text: value.toExponential(decimals ?? undefined) };
}

View File

@@ -228,7 +228,7 @@ export function toDuration(size: number, decimals: DecimalCount, timeScale: Inte
let decimalsCount = 0;
if (decimals !== null && decimals !== undefined) {
decimalsCount = decimals as number;
decimalsCount = decimals;
}
for (let i = 0; i < UNITS.length && decimalsCount >= 0; i++) {

View File

@@ -127,7 +127,7 @@ export function isBooleanUnit(unit?: string) {
}
export function booleanValueFormatter(t: string, f: string): ValueFormatter {
return (value: any) => {
return (value) => {
return { text: value ? t : f };
};
}
@@ -159,7 +159,7 @@ export function locale(value: number, decimals: DecimalCount): FormattedValue {
return { text: '' };
}
return {
text: value.toLocaleString(undefined, { maximumFractionDigits: decimals as number }),
text: value.toLocaleString(undefined, { maximumFractionDigits: decimals ?? undefined }),
};
}

View File

@@ -34,7 +34,7 @@ export const getMockPlugins = (amount: number): PluginMeta[] => {
});
}
return plugins as any;
return plugins;
};
export function getPanelPlugin(

View File

@@ -68,7 +68,7 @@ const ButtonSelectComponent = <T,>(props: Props<T>) => {
{options.map((item) => (
<MenuItem
key={`${item.value}`}
label={(item.label || item.value) as string}
label={item.label ?? String(item.value)}
onClick={() => onChangeInternal(item)}
active={item.value === value?.value}
ariaChecked={item.value === value?.value}

View File

@@ -9,7 +9,7 @@ import { VizTooltip } from '../VizTooltip';
import Graph from './Graph';
const display: DisplayProcessor = (v) => ({ numeric: v, text: String(v), color: 'red' });
const display: DisplayProcessor = (v) => ({ numeric: Number(v), text: String(v), color: 'red' });
const series: GraphSeriesXY[] = [
{

View File

@@ -11,7 +11,7 @@ import { GraphDimensions } from './types';
let dimensions: GraphDimensions;
describe('MultiModeGraphTooltip', () => {
const display: DisplayProcessor = (v) => ({ numeric: v, text: String(v), color: 'red' });
const display: DisplayProcessor = (v) => ({ numeric: Number(v), text: String(v), color: 'red' });
const theme = createTheme();
describe('when shown when hovering over a datapoint', () => {

View File

@@ -187,7 +187,7 @@ export function initIconCache() {
// This function needs to be called after index.js loads to give the
// application time to modify __webpack_public_path__ with a CDN path
const grafanaPublicPath = typeof window !== 'undefined' && (window as any).__grafana_public_path__;
const grafanaPublicPath = typeof window !== 'undefined' && window.__grafana_public_path__;
if (grafanaPublicPath) {
iconRoot = grafanaPublicPath + 'img/icons/';
}

View File

@@ -24,14 +24,14 @@ export function initIconCache() {
// This function needs to be called after index.js loads to give the
// application time to modify __webpack_public_path__ with a CDN path
const grafanaPublicPath = typeof window !== 'undefined' && (window as any).__grafana_public_path__;
const grafanaPublicPath = typeof window !== 'undefined' && window.__grafana_public_path__;
if (grafanaPublicPath) {
iconRoot = grafanaPublicPath + 'img/icons/';
}
// do not edit this list directly
// the list of icons live here: @grafana/ui/components/Icon/cached.json
// do not edit this list directly
// the list of icons live here: @grafana/ui/components/Icon/cached.json
//{{cacheItems}}
// do not edit this list directly
// the list of icons live here: @grafana/ui/components/Icon/cached.json
// do not edit this list directly
// the list of icons live here: @grafana/ui/components/Icon/cached.json
}

View File

@@ -166,7 +166,7 @@ export function getColumns(
}
/*
Build `Field` data for row numbers and prepend to the field array;
Build `Field` data for row numbers and prepend to the field array;
this way, on other column's sort, the row numbers will persist in their proper place.
*/
export function buildFieldsForOptionalRowNums(totalRows: number): Field {
@@ -339,12 +339,12 @@ export function getFooterItems(
theme2: GrafanaTheme2
): FooterItem[] {
/*
Here, `filterFields` is passed as the `headerGroups[0].headers` array
that was destructured from the `useTable` hook. Unfortunately, since
the `headerGroups` object is data based ONLY on the rendered "non-hidden"
column headers, it will NOT include the Row Number column if it has been
Here, `filterFields` is passed as the `headerGroups[0].headers` array
that was destructured from the `useTable` hook. Unfortunately, since
the `headerGroups` object is data based ONLY on the rendered "non-hidden"
column headers, it will NOT include the Row Number column if it has been
toggled off. This will shift the rendering of the footer left 1 column,
creating an off-by-one issue. This is why we test for a `field.id` of "0".
creating an off-by-one issue. This is why we test for a `field.id` of "0".
If the condition is truthy, the togglable Row Number column is being rendered,
and we can proceed normally. If not, we must add the field data in its place
so that the footer data renders in the expected column.
@@ -356,26 +356,26 @@ export function getFooterItems(
filterFields = [fieldToAdd, ...filterFields];
}
/*
The FooterItems[] are calculated using both the `headerGroups[0].headers`
/*
The FooterItems[] are calculated using both the `headerGroups[0].headers`
(filterFields) and `rows` (values) destructured from the useTable() hook.
This cacluation is based on the data from each index in `filterFields`
array as well as the corresponding index in the `values` array.
When the user hides a column through an override, the getColumns()
hook is invoked, removes said hidden column, sends the updated column
data to the useTable() hook, which then builds `headerGroups[0].headers`
without the hidden column. However, it doesn't remove the hidden column
from the `row` data, instead it substututes the hidden column row data
with an `undefined` value. Therefore, the `row` array length never changes,
despite the `headerGroups[0].headers` length changing at every column removal.
This makes all footer reduce calculations AFTER the first hidden column
in the `headerGroups[0].headers` break, since the indexing of both
This cacluation is based on the data from each index in `filterFields`
array as well as the corresponding index in the `values` array.
When the user hides a column through an override, the getColumns()
hook is invoked, removes said hidden column, sends the updated column
data to the useTable() hook, which then builds `headerGroups[0].headers`
without the hidden column. However, it doesn't remove the hidden column
from the `row` data, instead it substututes the hidden column row data
with an `undefined` value. Therefore, the `row` array length never changes,
despite the `headerGroups[0].headers` length changing at every column removal.
This makes all footer reduce calculations AFTER the first hidden column
in the `headerGroups[0].headers` break, since the indexing of both
arrays is no longer in parity.
So, here we simply recursively test for the "hidden" columns
from `headerGroups[0].headers`. Each column has an ID property that corresponds
to its own index, therefore if (`filterField.id` !== `String(index)`),
we know there is one or more hidden columns; at which point we update
So, here we simply recursively test for the "hidden" columns
from `headerGroups[0].headers`. Each column has an ID property that corresponds
to its own index, therefore if (`filterField.id` !== `String(index)`),
we know there is one or more hidden columns; at which point we update
the index with an ersatz placeholder with just an `id` property.
*/
addMissingColumnIndex(filterFields);
@@ -499,15 +499,15 @@ export function migrateTableDisplayModeToCellOptions(displayMode: TableCellDispl
`values` property is omitted, as it will be added at a later time.
*/
export const defaultRowNumberColumnFieldData: Omit<Field, 'values'> = {
/*
/*
Single whitespace as value for `name` property so as to render an empty/invisible column header;
without the single whitespace, falsey headers (empty strings) are given a default name of "Value".
*/
name: ' ',
display: function (value: string) {
display: function (value) {
return {
numeric: Number(value),
text: value,
text: value != null ? String(value) : '',
};
},
type: FieldType.string,