Chore: Improve typings (#78940)

* improve typings

* transformations typings improvements

* add bootData to window

* more grafana-data fixes

* undo window.grafanaBootData typings
This commit is contained in:
Ashley Harrison
2023-12-05 10:26:23 +00:00
committed by GitHub
parent ed128ea964
commit 568d979dd5
22 changed files with 65 additions and 113 deletions

View File

@@ -46,7 +46,12 @@ describe('dataFrameView', () => {
it('Should support array indexes', () => {
expect(vector.length).toEqual(3);
const first = vector.get(0) as any;
const first = vector.get(0) as unknown as [
MySpecialObject['time'],
MySpecialObject['name'],
MySpecialObject['value'],
MySpecialObject['more'],
];
expect(first[0]).toEqual(100);
expect(first[1]).toEqual('a');
expect(first[2]).toEqual(1);
@@ -84,7 +89,10 @@ describe('dataFrameView', () => {
});
it('Can handle fields with number name', () => {
const view = new DataFrameView<MySpecialObject>(
const view = new DataFrameView<{
'1': string;
'2': string;
}>(
new MutableDataFrame({
fields: [
{ name: '1', type: FieldType.string, values: ['a'] },
@@ -93,7 +101,7 @@ describe('dataFrameView', () => {
})
);
const obj = view.get(0) as any;
const obj = view.get(0);
expect(obj['1']).toEqual('a');
expect(obj['2']).toEqual('b');
});

View File

@@ -162,7 +162,7 @@ export class MutableDataFrame<T = any> extends FunctionalVector<T> implements Da
return parser;
}
private parseValue(field: Field, v: any): any {
private parseValue(field: Field, v: string) {
let p = this.parsers?.get(field);
if (!p) {
p = this.setParser(field, makeFieldParser(v, field));

View File

@@ -123,7 +123,7 @@ export class StreamingDataFrame implements DataFrame {
dataFrameDTO.fields = dataFrameDTO.fields.map((f) => ({
...f,
values: (f.values as unknown[]).slice(numberOfItemsToRemove),
values: f.values?.slice(numberOfItemsToRemove),
}));
const length = dataFrameDTO.fields[0]?.values?.length ?? 0;

View File

@@ -17,8 +17,8 @@ export interface DataHoverPayload {
dataId?: string; // identifying string to correlate data between publishers and subscribers
// When dragging, this will capture the point when the mouse was down
point: Record<string, any>; // { time: 5678, lengthft: 456 } // each axis|scale gets a value
down?: Record<string, any>;
point: Record<string, number | null>; // { time: 5678, lengthft: 456 } // each axis|scale gets a value
down?: Record<string, number | null>;
}
/** @alpha */

View File

@@ -33,7 +33,7 @@ export const numberOverrideProcessor = (
};
export const displayNameOverrideProcessor = (
value: any,
value: unknown,
context: FieldOverrideContext,
settings?: StringFieldConfigSettings
) => {
@@ -100,14 +100,14 @@ export interface StringFieldConfigSettings {
}
export const stringOverrideProcessor = (
value: any,
value: unknown,
context: FieldOverrideContext,
settings?: StringFieldConfigSettings
) => {
if (value === null || value === undefined) {
return value;
}
if (settings && settings.expandTemplateVars && context.replaceVariables) {
if (settings && settings.expandTemplateVars && context.replaceVariables && typeof value === 'string') {
return context.replaceVariables(value, context.field!.state!.scopedVars);
}
return `${value}`;

View File

@@ -9,7 +9,7 @@ import { getActiveThresholdForValue } from './thresholds';
export interface ColorScaleValue {
percent: number; // 0-1
threshold: Threshold;
threshold: Threshold | undefined;
color: string;
}
@@ -49,13 +49,13 @@ function getBooleanScaleCalculator(field: Field, theme: GrafanaTheme2): ScaleCal
const trueValue: ColorScaleValue = {
color: theme.visualization.getColorByName('green'),
percent: 1,
threshold: undefined as unknown as Threshold,
threshold: undefined,
};
const falseValue: ColorScaleValue = {
color: theme.visualization.getColorByName('red'),
percent: 0,
threshold: undefined as unknown as Threshold,
threshold: undefined,
};
const mode = getFieldColorModeForField(field);

View File

@@ -111,11 +111,10 @@ export function filterFieldConfigOverrides(
.filter((x) => x.properties.length > 0);
}
function cleanProperties(obj: any, parentPath: string, fieldConfigRegistry: FieldConfigOptionsRegistry) {
function cleanProperties(obj: object, parentPath: string, fieldConfigRegistry: FieldConfigOptionsRegistry) {
let found = false;
for (const propName of Object.keys(obj)) {
const value = obj[propName];
for (const [propName, value] of Object.entries(obj)) {
const fullPath = `${parentPath}${propName}`;
const existsInRegistry = !!fieldConfigRegistry.getIfExists(fullPath);

View File

@@ -117,7 +117,7 @@ export const groupByTransformer: DataTransformerInfo<GroupByTransformerOptions>
const fields: Field[] = [];
for (const field of groupByFields) {
const values: any[] = [];
const values: unknown[] = [];
const fieldName = getFieldDisplayName(field);
valuesByGroupKey.forEach((value) => {
@@ -142,7 +142,7 @@ export const groupByTransformer: DataTransformerInfo<GroupByTransformerOptions>
const fieldName = getFieldDisplayName(field);
const aggregations = options.fields[fieldName].aggregations;
const valuesByAggregation: Record<string, any[]> = {};
const valuesByAggregation: Record<string, unknown[]> = {};
valuesByGroupKey.forEach((value) => {
const fieldWithValuesForGroup = value[fieldName];

View File

@@ -89,7 +89,7 @@ export const groupingToMatrixTransformer: DataTransformerInfo<GroupingToMatrixTr
const columnValues = uniqueValues(keyColumnField.values);
const rowValues = uniqueValues(keyRowField.values);
const matrixValues: { [key: string]: { [key: string]: any } } = {};
const matrixValues: { [key: string]: { [key: string]: unknown } } = {};
for (let index = 0; index < valueField.values.length; index++) {
const columnName = keyColumnField.values[index];

View File

@@ -38,7 +38,7 @@ export const histogramBucketSizes = [
];
/* eslint-enable */
const histFilter = [null];
const histFilter: number[] = [];
const histSort = (a: number, b: number) => a - b;
export interface HistogramTransformerInputs {
@@ -496,7 +496,7 @@ export function incrRoundDn(num: number, incr: number) {
function histogram(
vals: number[],
getBucket: (v: number) => number,
filterOut?: any[] | null,
filterOut?: number[],
sort?: ((a: number, b: number) => number) | null
): AlignedData {
let hist = new Map();

View File

@@ -73,7 +73,7 @@ export const mergeTransformer: DataTransformerInfo<MergeTransformerOptions> = {
return dataFrames;
}
const valuesByKey: Record<string, Array<Record<string, any>>> = {};
const valuesByKey: Record<string, Array<Record<string, unknown>>> = {};
const valuesInOrder: ValuePointer[] = [];
const keyFactory = createKeyFactory(data, fieldIndexByName, fieldNamesForKey);
const valueMapper = createValueMapper(data, fieldNames, fieldIndexByName);
@@ -157,7 +157,7 @@ const createValueMapper = (
fieldIndexByName: Record<string, Record<number, number>>
) => {
return (frameIndex: number, valueIndex: number) => {
const value: Record<string, any> = {};
const value: Record<string, unknown> = {};
const fieldNames = Array.from(fieldByName);
for (const fieldName of fieldNames) {
@@ -188,7 +188,7 @@ const createValueMapper = (
};
};
const isMergable = (existing: Record<string, any>, value: Record<string, any>): boolean => {
const isMergable = (existing: Record<string, unknown>, value: Record<string, unknown>): boolean => {
let mergable = true;
for (const prop in value) {
@@ -217,7 +217,7 @@ const fieldExistsInAllFrames = (
return Object.keys(fieldIndexByName[field.name]).length === data.length;
};
const createPointer = (key: string, valuesByKey: Record<string, Array<Record<string, any>>>): ValuePointer => {
const createPointer = (key: string, valuesByKey: Record<string, Array<Record<string, unknown>>>): ValuePointer => {
return {
key,
index: valuesByKey[key].length - 1,

View File

@@ -1,6 +1,6 @@
// mutates all nulls -> undefineds in the fieldValues array for value-less refValues ranges below maxThreshold
// refValues is typically a time array and maxThreshold is the allowable distance between in time
export function nullToUndefThreshold(refValues: number[], fieldValues: any[], maxThreshold: number): any[] {
export function nullToUndefThreshold(refValues: number[], fieldValues: unknown[], maxThreshold: number) {
let prevRef;
let nullIdx;
@@ -12,8 +12,8 @@ export function nullToUndefThreshold(refValues: number[], fieldValues: any[], ma
nullIdx = i;
}
} else {
if (nullIdx != null) {
if (refValues[i] - (prevRef as number) < maxThreshold) {
if (nullIdx != null && prevRef != null) {
if (refValues[i] - prevRef < maxThreshold) {
while (nullIdx < i) {
fieldValues[nullIdx++] = undefined;
}

View File

@@ -203,7 +203,7 @@ export class GrafanaPlugin<T extends PluginMeta = PluginMeta> {
/**
* @deprecated -- this is no longer necessary and will be removed
*/
setChannelSupport(support: any) {
setChannelSupport() {
console.warn('[deprecation] plugin is using ignored option: setChannelSupport', this.meta);
return this;
}

View File

@@ -94,7 +94,7 @@ export const onUpdateDatasourceResetOption =
export function updateDatasourcePluginOption<J extends DataSourceJsonData, S extends {} = KeyValue>(
props: DataSourcePluginOptionsEditorProps<J, S>,
key: keyof DataSourceSettings,
val: any
val: unknown
) {
const config = props.options;
@@ -107,7 +107,7 @@ export function updateDatasourcePluginOption<J extends DataSourceJsonData, S ext
export const updateDatasourcePluginJsonDataOption = <J extends DataSourceJsonData, S, K extends keyof J>(
props: DataSourcePluginOptionsEditorProps<J, S>,
key: K,
val: any
val: unknown
) => {
const config = props.options;
@@ -123,7 +123,7 @@ export const updateDatasourcePluginJsonDataOption = <J extends DataSourceJsonDat
export const updateDatasourcePluginSecureJsonDataOption = <J extends DataSourceJsonData, S extends {} = KeyValue>(
props: DataSourcePluginOptionsEditorProps<J, S>,
key: string,
val: any
val: unknown
) => {
const config = props.options;

View File

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

View File

@@ -69,7 +69,7 @@ const assureBaseUrl = (url: string): string => {
* @param searchParamsToUpdate
* @returns
*/
const getUrlForPartial = (location: Location<any>, searchParamsToUpdate: Record<string, any>) => {
const getUrlForPartial = (location: Location<any>, searchParamsToUpdate: UrlQueryMap) => {
const searchParams = urlUtil.parseKeyValue(
location.search.startsWith('?') ? location.search.substring(1) : location.search
);

View File

@@ -54,7 +54,7 @@ function toUrlParams(a: any, encodeAsAngularJS = true) {
encodeURIComponentAsAngularJS(value, pctEncodeSpaces)
: (value: EncodeURIComponentParams, _: boolean) => encodeURIComponent(value);
const isArray = (obj: any) => {
const isArray = (obj: unknown) => {
return Object.prototype.toString.call(obj) === '[object Array]';
};

View File

@@ -122,7 +122,7 @@ export class CircularVector<T = any> extends FunctionalVector<T> {
return this.buffer[(index + this.index) % this.buffer.length];
}
set(index: number, value: any) {
set(index: number, value: T) {
this.buffer[(index + this.index) % this.buffer.length] = value;
}

View File

@@ -18,7 +18,7 @@ export abstract class FunctionalVector<T = any> implements Vector<T> {
}
}
set(index: number, value: any): void {
set(index: number, value: T): void {
throw 'unsupported operation';
}