Chore: Improve typings (#88282)

* remove some type assertions

* some more type assertion fixes

* nicer

* shortcircuit while loop when hitting something that isn't an HTMLElement
This commit is contained in:
Ashley Harrison 2024-05-28 13:20:57 +01:00 committed by GitHub
parent c8ab138dbf
commit f1dbe39533
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 67 additions and 105 deletions

View File

@ -64,16 +64,13 @@ exports[`better eslint`] = {
[0, 0, 0, "Unexpected any. Specify a different type.", "10"],
[0, 0, 0, "Do not use any type assertions.", "11"],
[0, 0, 0, "Unexpected any. Specify a different type.", "12"],
[0, 0, 0, "Do not use any type assertions.", "13"],
[0, 0, 0, "Unexpected any. Specify a different type.", "14"],
[0, 0, 0, "Unexpected any. Specify a different type.", "13"],
[0, 0, 0, "Do not use any type assertions.", "14"],
[0, 0, 0, "Do not use any type assertions.", "15"],
[0, 0, 0, "Do not use any type assertions.", "16"],
[0, 0, 0, "Do not use any type assertions.", "17"],
[0, 0, 0, "Do not use any type assertions.", "18"],
[0, 0, 0, "Do not use any type assertions.", "19"],
[0, 0, 0, "Do not use any type assertions.", "20"],
[0, 0, 0, "Do not use any type assertions.", "21"],
[0, 0, 0, "Do not use any type assertions.", "22"]
[0, 0, 0, "Do not use any type assertions.", "19"]
],
"packages/grafana-data/src/datetime/datemath.ts:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"],
@ -83,9 +80,6 @@ exports[`better eslint`] = {
"packages/grafana-data/src/datetime/durationutil.ts:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"]
],
"packages/grafana-data/src/datetime/formatter.ts:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"]
],
"packages/grafana-data/src/datetime/moment_wrapper.ts:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"],
[0, 0, 0, "Do not use any type assertions.", "1"],
@ -97,17 +91,6 @@ exports[`better eslint`] = {
[0, 0, 0, "Do not use any type assertions.", "7"],
[0, 0, 0, "Do not use any type assertions.", "8"]
],
"packages/grafana-data/src/datetime/parser.ts:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"],
[0, 0, 0, "Do not use any type assertions.", "1"],
[0, 0, 0, "Do not use any type assertions.", "2"],
[0, 0, 0, "Do not use any type assertions.", "3"],
[0, 0, 0, "Do not use any type assertions.", "4"],
[0, 0, 0, "Do not use any type assertions.", "5"],
[0, 0, 0, "Do not use any type assertions.", "6"],
[0, 0, 0, "Do not use any type assertions.", "7"],
[0, 0, 0, "Do not use any type assertions.", "8"]
],
"packages/grafana-data/src/events/EventBus.ts:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"],
[0, 0, 0, "Unexpected any. Specify a different type.", "1"]
@ -130,13 +113,10 @@ exports[`better eslint`] = {
"packages/grafana-data/src/field/overrides/processors.ts:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"],
[0, 0, 0, "Unexpected any. Specify a different type.", "1"],
[0, 0, 0, "Do not use any type assertions.", "2"],
[0, 0, 0, "Unexpected any. Specify a different type.", "2"],
[0, 0, 0, "Unexpected any. Specify a different type.", "3"],
[0, 0, 0, "Do not use any type assertions.", "4"],
[0, 0, 0, "Unexpected any. Specify a different type.", "5"],
[0, 0, 0, "Unexpected any. Specify a different type.", "6"],
[0, 0, 0, "Unexpected any. Specify a different type.", "7"],
[0, 0, 0, "Do not use any type assertions.", "8"]
[0, 0, 0, "Unexpected any. Specify a different type.", "4"],
[0, 0, 0, "Unexpected any. Specify a different type.", "5"]
],
"packages/grafana-data/src/field/standardFieldConfigEditorRegistry.ts:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"],
@ -158,8 +138,7 @@ exports[`better eslint`] = {
[0, 0, 0, "Unexpected any. Specify a different type.", "3"],
[0, 0, 0, "Unexpected any. Specify a different type.", "4"],
[0, 0, 0, "Unexpected any. Specify a different type.", "5"],
[0, 0, 0, "Do not use any type assertions.", "6"],
[0, 0, 0, "Do not use any type assertions.", "7"]
[0, 0, 0, "Do not use any type assertions.", "6"]
],
"packages/grafana-data/src/panel/registryFactories.ts:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"]
@ -196,10 +175,6 @@ exports[`better eslint`] = {
[0, 0, 0, "Unexpected any. Specify a different type.", "0"],
[0, 0, 0, "Unexpected any. Specify a different type.", "1"]
],
"packages/grafana-data/src/transformations/transformers/utils.ts:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"],
[0, 0, 0, "Unexpected any. Specify a different type.", "1"]
],
"packages/grafana-data/src/types/OptionsUIRegistryBuilder.ts:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"],
[0, 0, 0, "Unexpected any. Specify a different type.", "1"],
@ -492,9 +467,6 @@ exports[`better eslint`] = {
"packages/grafana-prometheus/src/gcopypaste/public/test/matchers/utils.ts:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"]
],
"packages/grafana-prometheus/src/gcopypaste/test/helpers/selectOptionInTest.ts:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"]
],
"packages/grafana-prometheus/src/language_provider.ts:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"],
[0, 0, 0, "Unexpected any. Specify a different type.", "1"],
@ -583,8 +555,7 @@ exports[`better eslint`] = {
[0, 0, 0, "Do not use any type assertions.", "0"]
],
"packages/grafana-runtime/src/utils/DataSourceWithBackend.ts:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"],
[0, 0, 0, "Unexpected any. Specify a different type.", "1"]
[0, 0, 0, "Unexpected any. Specify a different type.", "0"]
],
"packages/grafana-runtime/src/utils/queryResponse.ts:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"]
@ -607,9 +578,6 @@ exports[`better eslint`] = {
"packages/grafana-sql/src/components/visual-query-builder/AwesomeQueryBuilder.tsx:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"]
],
"packages/grafana-sql/src/components/visual-query-builder/SQLWhereRow.tsx:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"]
],
"packages/grafana-ui/src/components/ColorPicker/ColorPicker.tsx:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"],
[0, 0, 0, "Unexpected any. Specify a different type.", "1"]
@ -788,9 +756,7 @@ exports[`better eslint`] = {
],
"packages/grafana-ui/src/components/VizRepeater/VizRepeater.tsx:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"],
[0, 0, 0, "Do not use any type assertions.", "1"],
[0, 0, 0, "Do not use any type assertions.", "2"],
[0, 0, 0, "Do not use any type assertions.", "3"]
[0, 0, 0, "Do not use any type assertions.", "1"]
],
"packages/grafana-ui/src/components/VizTooltip/VizTooltip.tsx:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"],
@ -807,9 +773,7 @@ exports[`better eslint`] = {
"packages/grafana-ui/src/components/uPlot/config/UPlotAxisBuilder.ts:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"],
[0, 0, 0, "Do not use any type assertions.", "1"],
[0, 0, 0, "Unexpected any. Specify a different type.", "2"],
[0, 0, 0, "Do not use any type assertions.", "3"],
[0, 0, 0, "Unexpected any. Specify a different type.", "4"]
[0, 0, 0, "Unexpected any. Specify a different type.", "2"]
],
"packages/grafana-ui/src/components/uPlot/config/UPlotConfigBuilder.ts:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"],
@ -820,8 +784,7 @@ exports[`better eslint`] = {
],
"packages/grafana-ui/src/components/uPlot/utils.ts:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"],
[0, 0, 0, "Do not use any type assertions.", "1"],
[0, 0, 0, "Unexpected any. Specify a different type.", "2"]
[0, 0, 0, "Unexpected any. Specify a different type.", "1"]
],
"packages/grafana-ui/src/graveyard/Graph/GraphContextMenu.tsx:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"]
@ -1156,9 +1119,6 @@ exports[`better eslint`] = {
[0, 0, 0, "Styles should be written using objects.", "1"],
[0, 0, 0, "Styles should be written using objects.", "2"]
],
"public/app/features/admin/OrgRolePicker.tsx:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"]
],
"public/app/features/admin/UpgradePage.tsx:5381": [
[0, 0, 0, "Styles should be written using objects.", "0"],
[0, 0, 0, "Styles should be written using objects.", "1"],
@ -2069,9 +2029,6 @@ exports[`better eslint`] = {
"public/app/features/dimensions/utils.ts:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"]
],
"public/app/features/explore/ContentOutline/ContentOutline.tsx:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"]
],
"public/app/features/explore/Logs/LiveLogs.tsx:5381": [
[0, 0, 0, "Styles should be written using objects.", "0"],
[0, 0, 0, "Styles should be written using objects.", "1"],

View File

@ -149,7 +149,7 @@ function convertGraphSeriesToDataFrame(graphSeries: GraphSeriesXY): DataFrame {
}
function convertJSONDocumentDataToDataFrame(timeSeries: TimeSeries): DataFrame {
const fields = [
const fields: Field[] = [
{
name: timeSeries.target,
type: FieldType.other,
@ -158,7 +158,7 @@ function convertJSONDocumentDataToDataFrame(timeSeries: TimeSeries): DataFrame {
unit: timeSeries.unit,
filterable: (timeSeries as any).filterable,
},
values: [] as TimeSeriesValue[][],
values: [],
},
];
@ -315,11 +315,11 @@ export function toDataFrame(data: any): DataFrame {
if ('fields' in data) {
// DataFrameDTO does not have length
if ('length' in data && data.fields[0]?.values?.get) {
return data as DataFrame;
return data;
}
// This will convert the array values into Vectors
return createDataFrame(data as DataFrameDTO);
return createDataFrame(data);
}
// Handle legacy docs/json type

View File

@ -1,11 +1,11 @@
/* eslint-disable id-blacklist, no-restricted-imports, @typescript-eslint/ban-types */
import moment, { MomentInput, Moment } from 'moment-timezone';
import moment, { Moment } from 'moment-timezone';
import { TimeZone } from '../types';
import { DateTimeOptions, getTimeZone } from './common';
import { systemDateFormats } from './formats';
import { DateTimeInput } from './moment_wrapper';
import { DateTimeInput, toUtc, dateTimeAsMoment } from './moment_wrapper';
/**
* The type describing the options that can be passed to the {@link dateTimeFormat}
@ -93,17 +93,17 @@ const getFormat = <T extends DateTimeOptionsWithFormat>(options?: T): string =>
};
const toTz = (dateInUtc: DateTimeInput, timeZone: TimeZone): Moment => {
const date = dateInUtc as MomentInput;
const date = dateInUtc;
const zone = moment.tz.zone(timeZone);
if (zone && zone.name) {
return moment.utc(date).tz(zone.name);
return dateTimeAsMoment(toUtc(date)).tz(zone.name);
}
switch (timeZone) {
case 'utc':
return moment.utc(date);
return dateTimeAsMoment(toUtc(date));
default:
return moment.utc(date).local();
return dateTimeAsMoment(toUtc(date)).local();
}
};

View File

@ -1,11 +1,11 @@
/* eslint-disable id-blacklist, no-restricted-imports, @typescript-eslint/ban-types */
import { lowerCase } from 'lodash';
import moment, { MomentInput } from 'moment-timezone';
import moment from 'moment-timezone';
import { DateTimeOptions, getTimeZone } from './common';
import { parse, isValid } from './datemath';
import { systemDateFormats } from './formats';
import { DateTimeInput, DateTime, isDateTime } from './moment_wrapper';
import { DateTimeInput, DateTime, isDateTime, dateTime, toUtc, dateTimeForTimeZone } from './moment_wrapper';
/**
* The type that describes options that can be passed when parsing a date and time value.
@ -55,11 +55,11 @@ export const dateTimeParse: DateTimeParser<DateTimeOptionsWhenParsing> = (value,
const parseString = (value: string, options?: DateTimeOptionsWhenParsing): DateTime => {
if (value.indexOf('now') !== -1) {
if (!isValid(value)) {
return moment() as DateTime;
return dateTime();
}
const parsed = parse(value, options?.roundUp, options?.timeZone, options?.fiscalYearStartMonth);
return parsed || (moment() as DateTime);
return parsed || dateTime();
}
const timeZone = getTimeZone(options);
@ -67,30 +67,30 @@ const parseString = (value: string, options?: DateTimeOptionsWhenParsing): DateT
const format = options?.format ?? systemDateFormats.fullDate;
if (zone && zone.name) {
return moment.tz(value, format, zone.name) as DateTime;
return dateTimeForTimeZone(zone.name, value, format);
}
switch (lowerCase(timeZone)) {
case 'utc':
return moment.utc(value, format) as DateTime;
return toUtc(value, format);
default:
return moment(value, format) as DateTime;
return dateTime(value, format);
}
};
const parseOthers = (value: DateTimeInput, options?: DateTimeOptionsWhenParsing): DateTime => {
const date = value as MomentInput;
const date = value;
const timeZone = getTimeZone(options);
const zone = moment.tz.zone(timeZone);
if (zone && zone.name) {
return moment.tz(date, zone.name) as DateTime;
return dateTimeForTimeZone(zone.name, date);
}
switch (lowerCase(timeZone)) {
case 'utc':
return moment.utc(date) as DateTime;
return toUtc(date);
default:
return moment(date) as DateTime;
return dateTime(date);
}
};

View File

@ -57,8 +57,8 @@ export const dataLinksOverrideProcessor = (
value: any,
_context: FieldOverrideContext,
_settings?: DataLinksFieldConfigSettings
) => {
return value as DataLink[];
): DataLink[] => {
return value;
};
export interface ValueMappingFieldConfigSettings {}
@ -67,8 +67,8 @@ export const valueMappingsOverrideProcessor = (
value: any,
_context: FieldOverrideContext,
_settings?: ValueMappingFieldConfigSettings
) => {
return value as ValueMapping[]; // !!!! likely not !!!!
): ValueMapping[] => {
return value; // !!!! likely not !!!!
};
export interface SelectFieldConfigSettings<T> {
@ -121,8 +121,8 @@ export const thresholdsOverrideProcessor = (
value: any,
_context: FieldOverrideContext,
_settings?: ThresholdsFieldConfigSettings
) => {
return value as ThresholdsConfig; // !!!! likely not !!!!
): ThresholdsConfig => {
return value; // !!!! likely not !!!!
};
export interface UnitFieldConfigSettings {

View File

@ -263,7 +263,7 @@ export class PanelPlugin<
* @internal
*/
getPanelOptionsSupplier(): PanelOptionsSupplier<TOptions> {
return this.optionsSupplier ?? ((() => {}) as PanelOptionsSupplier<TOptions>);
return this.optionsSupplier ?? (() => {});
}
/**

View File

@ -1,7 +1,13 @@
import { DataFrame } from '../../types';
import { BootData, DataFrame } from '../../types';
declare global {
interface Window {
grafanaBootData?: BootData;
}
}
export const transformationsVariableSupport = () => {
return (window as any)?.grafanaBootData?.settings?.featureToggles?.transformationsVariableSupport;
return window?.grafanaBootData?.settings?.featureToggles?.transformationsVariableSupport;
};
/**

View File

@ -1,5 +1,5 @@
// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/packages/grafana-ui/src/components/Select/SelectBase.tsx
import { Matcher, waitFor } from '@testing-library/react';
import { waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { select } from 'react-select-event';
import { byRole } from 'testing-library-selector';
@ -18,7 +18,3 @@ export const clickSelectOption = async (selectElement: HTMLElement, optionText:
await userEvent.click(byRole('combobox').get(selectElement));
await selectOptionInTest(selectElement, optionText);
};
export const clickSelectOptionMatch = async (selectElement: HTMLElement, optionText: Matcher): Promise<void> => {
await userEvent.click(byRole('combobox').get(selectElement));
await selectOptionInTest(selectElement, optionText as string);
};

View File

@ -137,7 +137,7 @@ class DataSourceWithBackend<
let hasExpr = false;
const pluginIDs = new Set<string>();
const dsUIDs = new Set<string>();
const queries = targets.map((q) => {
const queries: DataQuery[] = targets.map((q) => {
let datasource = this.getRef();
let datasourceId = this.id;
let shouldApplyTemplateVariables = true;
@ -255,7 +255,7 @@ class DataSourceWithBackend<
})
.pipe(
switchMap((raw) => {
const rsp = toDataQueryResponse(raw, queries as DataQuery[]);
const rsp = toDataQueryResponse(raw, queries);
// Check if any response should subscribe to a live stream
if (rsp.data?.length && rsp.data.find((f: DataFrame) => f.meta?.channel)) {
return toStreamingDataResponse(rsp, request, this.streamOptionsProvider);

View File

@ -1,7 +1,7 @@
import React from 'react';
import useAsync from 'react-use/lib/useAsync';
import { SelectableValue, VariableWithMultiSupport } from '@grafana/data';
import { SelectableValue, TypedVariableModel } from '@grafana/data';
import { getTemplateSrv } from '@grafana/runtime';
import { QueryWithDefaults } from '../../defaults';
@ -32,7 +32,8 @@ export function SQLWhereRow({ query, fields, onQueryChange, db }: WhereRowProps)
config={{ fields: state.value || {} }}
sql={query.sql!}
onSqlChange={(val: SQLExpression) => {
const templateVars = getTemplateSrv().getVariables() as VariableWithMultiSupport[];
const templateVars = getTemplateSrv().getVariables();
removeQuotesForMultiVariables(val, templateVars);
onSqlChange(val);
@ -54,9 +55,11 @@ function mapFieldsToTypes(columns: SQLSelectableValue[]) {
return fields;
}
export function removeQuotesForMultiVariables(val: SQLExpression, templateVars: VariableWithMultiSupport[]) {
const multiVariableInWhereString = (tv: VariableWithMultiSupport) =>
tv.multi && (val.whereString?.includes(`\${${tv.name}}`) || val.whereString?.includes(`$${tv.name}`));
export function removeQuotesForMultiVariables(val: SQLExpression, templateVars: TypedVariableModel[]) {
const multiVariableInWhereString = (tv: TypedVariableModel) =>
'multi' in tv &&
tv.multi &&
(val.whereString?.includes(`\${${tv.name}}`) || val.whereString?.includes(`$${tv.name}`));
if (templateVars.some((tv) => multiVariableInWhereString(tv))) {
val.whereString = val.whereString?.replaceAll("')", ')');

View File

@ -54,12 +54,12 @@ interface State<V> {
values: V[];
}
export class VizRepeater<V, D = {}> extends PureComponent<Props<V, D>, State<V>> {
export class VizRepeater<V, D = {}> extends PureComponent<PropsWithDefaults<V, D>, State<V>> {
static defaultProps: DefaultProps = {
itemSpacing: 8,
};
constructor(props: Props<V, D>) {
constructor(props: PropsWithDefaults<V, D>) {
super(props);
this.state = {
@ -89,8 +89,7 @@ export class VizRepeater<V, D = {}> extends PureComponent<Props<V, D>, State<V>>
}
renderGrid() {
const { renderValue, height, width, itemSpacing, getAlignmentFactors, orientation } = this
.props as PropsWithDefaults<V, D>;
const { renderValue, height, width, itemSpacing, getAlignmentFactors, orientation } = this.props;
const { values } = this.state;
const grid = calculateGridDimensions(width, height, itemSpacing, values.length);
@ -154,7 +153,7 @@ export class VizRepeater<V, D = {}> extends PureComponent<Props<V, D>, State<V>>
maxVizHeight,
minVizWidth,
minVizHeight,
} = this.props as PropsWithDefaults<V, D>;
} = this.props;
const { values } = this.state;
if (autoGrid && orientation === VizOrientation.Auto) {

View File

@ -231,7 +231,8 @@ export function formatTime(
foundSpace: number,
foundIncr: number
): string[] {
const timeZone = (self.axes[axisIdx] as any).timeZone;
const axis = self.axes[axisIdx];
const timeZone = 'timeZone' in axis && typeof axis.timeZone === 'string' ? axis.timeZone : undefined;
const scale = self.scales.x;
const range = (scale?.max ?? 0) - (scale?.min ?? 0);
const yearRoundedToDay = Math.round(timeUnitSize.year / timeUnitSize.day) * timeUnitSize.day;

View File

@ -260,7 +260,7 @@ export function preparePlotData2(
});
onStackMeta({
totals: accumsBySeriesIdx as AlignedData,
totals: accumsBySeriesIdx,
});
}

View File

@ -22,7 +22,7 @@ export function OrgRolePicker({ value, onChange, 'aria-label': ariaLabel, inputI
inputId={inputId}
value={value}
options={options}
onChange={(val) => onChange(val.value as OrgRole)}
onChange={(val) => onChange(val.value ?? OrgRole.None)}
placeholder="Choose role..."
aria-label={ariaLabel}
autoFocus={autoFocus}

View File

@ -60,7 +60,7 @@ export function ContentOutline({ scroller, panelId }: { scroller: HTMLElement |
do {
scrollValue += el?.offsetTop || 0;
el = el?.offsetParent as HTMLElement;
el = el?.offsetParent instanceof HTMLElement ? el.offsetParent : undefined;
} while (el && el !== scroller);
scroller?.scroll({