The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Remove @ts-nocheck from metabase-lib Field (#76320)
Romeo Van Snick1df9e0765195
diff --git a/frontend/src/metabase-lib/v1/metadata/Base.ts b/frontend/src/metabase-lib/v1/metadata/Base.tsdeleted file mode 100644index a9bbfdcb2bb..00000000000--- a/frontend/src/metabase-lib/v1/metadata/Base.ts+++ /dev/null@@ -1,22 +0,0 @@-// eslint-disable-next-line @typescript-eslint/ban-ts-comment-// @ts-nocheck-// eslint-disable-next-line import/no-default-export -- deprecated usage-export default class Base {- _plainObject: Record<string, unknown>;-- constructor(object = {}) {- this._plainObject = object;-- for (const property in object) {- this[property] = object[property];- }- }-- /**- * Get the plain metadata object without hydrated fields.- * Useful for situations where you want serialize the metadata object.- */- getPlainObject() {- return this._plainObject;- }-}diff --git a/frontend/src/metabase-lib/v1/metadata/Base.unit.spec.ts b/frontend/src/metabase-lib/v1/metadata/Base.unit.spec.tsdeleted file mode 100644index 348a6b95b02..00000000000--- a/frontend/src/metabase-lib/v1/metadata/Base.unit.spec.ts+++ /dev/null@@ -1,49 +0,0 @@-// eslint-disable-next-line @typescript-eslint/ban-ts-comment-// @ts-nocheck-import Base from "./Base";--describe("Base", () => {- describe("instantiation", () => {- it("should set properties from `object` on the Base instance", () => {- const instance = new Base({- abc: 123,- });- expect(instance.abc).toEqual(123);- });-- it("should set ALL enumerable properties of `object`, including properties down the prototype chain", () => {- const object = {- abc: 123,- };- Object.defineProperty(object, "anEnumerableProperty", {- enumerable: false,- value: false,- });- object.__proto__ = {- secretPrototypeValue: true,- };- const instance = new Base(object);- expect(instance.abc).toEqual(123);- expect(instance.secretPrototypeValue).toBe(true);- expect(instance.anEnumerableProperty).toBeUndefined();- });- });-- describe("getPlainObject", () => {- it("returns whatever `object` was provided during instantiation", () => {- const obj = {- abc: 123,- };- const instance = new Base(obj);- expect(instance.getPlainObject()).toBe(obj);- });-- it("returns whatever `_plainObject` is set to", () => {- const obj1 = {};- const obj2 = {};- const instance = new Base(obj1);- instance._plainObject = obj2;- expect(instance.getPlainObject()).toBe(obj2);- });- });-});diff --git a/frontend/src/metabase-lib/v1/metadata/Field.ts b/frontend/src/metabase-lib/v1/metadata/Field.tsindex 7cdc744d075..af1311cf230 100644--- a/frontend/src/metabase-lib/v1/metadata/Field.ts+++ b/frontend/src/metabase-lib/v1/metadata/Field.ts@@ -1,5 +1,3 @@-// eslint-disable-next-line @typescript-eslint/ban-ts-comment-// @ts-nocheckimport _ from "underscore";import { formatField, stripId } from "metabase/utils/formatting";@@ -26,58 +24,51 @@ import {isTime,} from "metabase-lib/v1/types/utils/isa";import type {+ Field as ApiField,FieldFingerprint,- FieldFormattingSettings,FieldId,FieldReference,- FieldValuesType,- FieldVisibilityType,NormalizedField,} from "metabase-types/api";-import Base from "./Base";import type Metadata from "./Metadata";import type Table from "./Table";import { getIconForField, getUniqueFieldId } from "./utils/fields";-/**- * @typedef { import("./Metadata").FieldValues } FieldValues- */+// This interface is intentionally empty: a class cannot `extends` a type alias,+// so merging an interface with the class is how instances inherit the API+// field's properties without re-declaring them. The class declares the rest.+//+// eslint-disable-next-line @typescript-eslint/no-empty-object-type+interface Field extends Omit<+ ApiField,+ "table" | "target" | "name_field" | "fingerprint"+> {}/*** Wrapper class for field metadata objects. Belongs to a Table.- */--/**+ ** @deprecated use RTK Query endpoints and plain api objects from metabase-types/api*/-// eslint-disable-next-line import/no-default-export-export default class Field extends Base {- id: FieldId | FieldReference;- name: string;- display_name: string;- description: string | null;- semantic_type: string | null;- fingerprint?: FieldFingerprint;- base_type: string;- effective_type?: string | null;+class Field {+ // `table`/`target`/`name_field` are id references in the plain object and are+ // hydrated into instances by the metadata layer (`hydrateField`), so these+ // types describe a hydrated field. Properties are copied from the plain object+ // by the constructor, or set by hydration.table?: Table;- table_id?: Table["id"];target?: Field;name_field?: Field;- remapping?: unknown;- has_field_values?: FieldValuesType;- has_more_values?: boolean;- values: any[];- position: number;+ fingerprint?: FieldFingerprint;+ _plainObject: NormalizedField;metadata?: Metadata;+ remapping?: Map<unknown, unknown>;source?: string;- nfc_path?: string[];- json_unfolding: boolean | null;- coercion_strategy: string | null;- fk_target_field_id: FieldId | null;- settings?: FieldFormattingSettings;- visibility_type: FieldVisibilityType;+ uniqueId?: string | number;++ constructor(object: NormalizedField) {+ this._plainObject = object;+ Object.assign(this, object);+ }getPlainObject(): NormalizedField {return this._plainObject;@@ -109,8 +100,8 @@ export default class Field extends Base {}path() {- const path = [];- let field = this;+ const path: Field[] = [];+ let field: Field | null = this;do {path.unshift(field);@@ -225,9 +216,6 @@ export default class Field extends Base {return isFK(this);}- /**- * @returns {FieldValues}- */fieldValues() {return getFieldValues(this._plainObject);}@@ -268,15 +256,11 @@ export default class Field extends Base {return null;}- /**- * Returns the remapped field, if any- * @return {?Field}- */remappedExternalField() {const displayFieldId = this.dimensions?.[0]?.human_readable_field_id;if (displayFieldId != null) {- return this.metadata.field(displayFieldId);+ return this.metadata?.field(displayFieldId) ?? null;}// enables "implicit" remapping from type/PK to type/Name on the same table,@@ -290,36 +274,27 @@ export default class Field extends Base {return null;}- /**- * Returns the human readable remapped value, if any- * @returns {?string}- */- remappedValue(value) {+ remappedValue(value: unknown) {// TODO: Ugh. Should this be handled further up by the parameter widget?- if (this.isNumeric() && typeof value !== "number") {- value = parseFloat(value);+ let key = value;+ if (this.isNumeric() && typeof key !== "number") {+ key = parseFloat(String(key));}- return this.remapping && this.remapping.get(value);+ return this.remapping && this.remapping.get(key);}- /**- * Returns whether the field has a human readable remapped value for this value- * @returns {?string}- */- hasRemappedValue(value) {+ hasRemappedValue(value: unknown) {// TODO: Ugh. Should this be handled further up by the parameter widget?- if (this.isNumeric() && typeof value !== "number") {- value = parseFloat(value);+ let key = value;+ if (this.isNumeric() && typeof key !== "number") {+ key = parseFloat(String(key));}- return this.remapping && this.remapping.has(value);+ return this.remapping && this.remapping.has(key);}- /**- * Returns true if this field can be searched, e.x. in filter or parameter widgets- * @returns {boolean}- */+ // Returns true if this field can be searched, e.g. in filter or parameter widgetsisSearchable() {// TODO: ...?return this.isString();@@ -338,14 +313,14 @@ export default class Field extends Base {return this.isSearchable() ? this : null;}- clone(fieldMetadata?: FieldMetadata) {+ clone(fieldMetadata?: Partial<NormalizedField>) {if (fieldMetadata instanceof Field) {throw new Error("`fieldMetadata` arg must be a plain object");}- const plainObject = this.getPlainObject();- const newField = new Field({ ...this, ...fieldMetadata });- newField._plainObject = { ...plainObject, ...fieldMetadata };+ const newField = new Field(this.getPlainObject());+ Object.assign(newField, this, fieldMetadata);+ newField._plainObject = { ...this.getPlainObject(), ...fieldMetadata };return newField;}@@ -354,26 +329,15 @@ export default class Field extends Base {return typeof this.id !== "number";}- /**- * @private- * @param {number} id- * @param {string} name- * @param {string} display_name- * @param {string} description- * @param {Table} table- * @param {?Field} name_field- * @param {Metadata} metadata- */-/* istanbul ignore next */_constructor(- id,- name,- display_name,- description,- table,- name_field,- metadata,+ id: FieldId | FieldReference,+ name: string,+ display_name: string,+ description: string | null,+ table: Table,+ name_field: Field,+ metadata: Metadata,) {this.id = id;this.name = name;@@ -384,3 +348,6 @@ export default class Field extends Base {this.metadata = metadata;}}++// eslint-disable-next-line import/no-default-export -- deprecated usage+export default Field;diff --git a/frontend/src/metabase-lib/v1/parameters/utils/filters.unit.spec.ts b/frontend/src/metabase-lib/v1/parameters/utils/filters.unit.spec.tsindex 05c7f0084bb..cf86461020c 100644--- a/frontend/src/metabase-lib/v1/parameters/utils/filters.unit.spec.ts+++ b/frontend/src/metabase-lib/v1/parameters/utils/filters.unit.spec.ts@@ -4,6 +4,7 @@ import Field from "metabase-lib/v1/metadata/Field";import type NativeQuery from "metabase-lib/v1/queries/NativeQuery";import {createMockNativeCard,+ createMockNormalizedField,createMockParameter,} from "metabase-types/api/mocks";@@ -160,7 +161,7 @@ describe("parameters/utils/field-filters", () => {});function createMockField(mocks: Record<string, unknown>): Field {- return Object.assign(new Field(), mocks);+ return Object.assign(new Field(createMockNormalizedField({})), mocks);}function createMockDimension(diff --git a/frontend/src/metabase-lib/v1/types/utils/isa.ts b/frontend/src/metabase-lib/v1/types/utils/isa.tsindex 1fb4230284f..a5ab9df467f 100644--- a/frontend/src/metabase-lib/v1/types/utils/isa.ts+++ b/frontend/src/metabase-lib/v1/types/utils/isa.ts@@ -29,6 +29,16 @@ export interface FieldTypeInfo {semantic_type?: string | null;}+/**+ * The subset of column properties needed to classify a column as a dimension+ * or metric. Satisfied by both Field and DatasetColumn.+ */+export interface ColumnClassificationInfo extends FieldTypeInfo {+ name: string;+ source?: string | null;+ binning_info?: DatasetColumn["binning_info"];+}+/*** Is x the same as, or a descendant type of, y?*@@ -132,14 +142,14 @@ export const isStringLike = (field: FieldTypeInfo | null | undefined) =>export const isSummable = (field: FieldTypeInfo | null | undefined) =>isFieldType(SUMMABLE, field);-const hasNonMetricName = (col: DatasetColumn) => {+const hasNonMetricName = (col: ColumnClassificationInfo) => {const name = col.name.toLowerCase();return name === "id" || name.endsWith("_id") || name.endsWith("-id");};-export const isDimension = (col: DatasetColumn) =>+export const isDimension = (col: ColumnClassificationInfo) =>col.source !== "aggregation" || !!col.binning_info; // columns with binning_info are always dimensions (they represent categorical buckets)-export const isMetric = (col: DatasetColumn) =>+export const isMetric = (col: ColumnClassificationInfo) =>col.source !== "breakout" &&isSummable(col) &&!hasNonMetricName(col) &&diff --git a/frontend/src/metabase/parameters/components/ParameterWidget/ParameterWidget.unit.spec.tsx b/frontend/src/metabase/parameters/components/ParameterWidget/ParameterWidget.unit.spec.tsxindex bc605766f39..5466f096c71 100644--- a/frontend/src/metabase/parameters/components/ParameterWidget/ParameterWidget.unit.spec.tsx+++ b/frontend/src/metabase/parameters/components/ParameterWidget/ParameterWidget.unit.spec.tsx@@ -5,7 +5,10 @@ import userEvent, {import { renderWithProviders, screen } from "__support__/ui";import Field from "metabase-lib/v1/metadata/Field";import type { FieldFilterUiParameter } from "metabase-lib/v1/parameters/types";-import { createMockField, createMockParameter } from "metabase-types/api/mocks";+import {+ createMockNormalizedField,+ createMockParameter,+} from "metabase-types/api/mocks";import { ParameterWidget } from "./ParameterWidget";@@ -73,7 +76,7 @@ describe("ParameterWidget", () => {it("should not be able to submit empty value when parameter has connected field (metabase#15462)", async () => {const field = new Field(- createMockField({+ createMockNormalizedField({id: 1,base_type: "type/Text",effective_type: "type/Text",diff --git a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetFieldMetadataSidebar/MappedFieldPicker/MappedFieldPicker.tsx b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetFieldMetadataSidebar/MappedFieldPicker/MappedFieldPicker.tsxindex c37d9032486..5db886d51ed 100644--- a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetFieldMetadataSidebar/MappedFieldPicker/MappedFieldPicker.tsx+++ b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetFieldMetadataSidebar/MappedFieldPicker/MappedFieldPicker.tsx@@ -1,6 +1,6 @@import cx from "classnames";import { useField } from "formik";-import { useCallback, useMemo, useRef } from "react";+import { useCallback, useRef } from "react";import { t } from "ttag";import { useGetFieldQuery } from "metabase/api";@@ -8,7 +8,6 @@ import { SelectButton } from "metabase/common/components/SelectButton";import CS from "metabase/css/core/index.css";import { SchemaTableAndFieldDataSelector } from "metabase/querying/common/components/DataSelector";import { Text } from "metabase/ui";-import Field from "metabase-lib/v1/metadata/Field";import { isVirtualCardId } from "metabase-lib/v1/metadata/utils/saved-questions";import type { FieldId } from "metabase-types/api";@@ -40,9 +39,7 @@ export function MappedFieldPicker({{ skip: selectedFieldId === null },);- const fieldObject = useMemo(() => {- return field && selectedFieldId ? new Field(field) : null;- }, [field, selectedFieldId]);+ const selectedField = field && selectedFieldId ? field : null;const selectButtonRef = useRef<HTMLButtonElement>();@@ -61,8 +58,8 @@ export function MappedFieldPicker({);const renderTriggerElement = useCallback(() => {- const label = fieldObject?.display_name || t`None`;- const tableName = fieldObject?.table?.display_name;+ const label = selectedField?.display_name || t`None`;+ const tableName = selectedField?.table?.display_name;return (<SelectButton@@ -70,13 +67,13 @@ export function MappedFieldPicker({root: cx(MappedFieldPickerS.StyledSelectButton,{- [MappedFieldPickerS.hasValue]: fieldObject,+ [MappedFieldPickerS.hasValue]: selectedField,},className,),icon: MappedFieldPickerS.StyledSelectIcon,}}- hasValue={!!fieldObject}+ hasValue={!!selectedField}tabIndex={tabIndex}ref={selectButtonRef as any}onClear={() => onChange(null)}@@ -86,17 +83,17 @@ export function MappedFieldPicker({</span></SelectButton>);- }, [className, fieldObject, onChange, tabIndex]);+ }, [className, selectedField, onChange, tabIndex]);// DataSelector doesn't handle selectedTableId change prop nicely.- // During the initial load, fieldObject might have `table_id` set to `card__$ID` (retrieved from metadata)+ // During the initial load, the field might have `table_id` set to `card__$ID` (retrieved from metadata)// But at some point, we fetch the field object by ID to get the real table ID and pass it to the selector// Until it's fetched, we need to pass `null` as `selectedTableId` to avoid invalid selector state// This should be removed once DataSelector handles prop changes betterconst selectedTableId =- !fieldObject || isVirtualCardId(fieldObject.table?.id)+ !selectedField || isVirtualCardId(selectedField.table?.id)? null- : fieldObject?.table?.id;+ : selectedField?.table?.id;return (<>@@ -113,7 +110,7 @@ export function MappedFieldPicker({)}selectedDatabaseId={databaseId}selectedTableId={selectedTableId}- selectedSchemaId={fieldObject?.table?.schema?.id}+ selectedSchemaId={selectedField?.table?.schema}selectedFieldId={selectedFieldId}getTriggerElementContent={renderTriggerElement}hasTriggerExpandControl={false}diff --git a/frontend/src/metabase/query_builder/model-indexes/utils.unit.spec.ts b/frontend/src/metabase/query_builder/model-indexes/utils.unit.spec.tsindex 72d44fe9b88..26a2f72a458 100644--- a/frontend/src/metabase/query_builder/model-indexes/utils.unit.spec.ts+++ b/frontend/src/metabase/query_builder/model-indexes/utils.unit.spec.ts@@ -1,7 +1,11 @@import Question from "metabase-lib/v1/Question";import Field from "metabase-lib/v1/metadata/Field";import type { Field as FieldAPI } from "metabase-types/api";-import { createMockCard, createMockField } from "metabase-types/api/mocks";+import {+ createMockCard,+ createMockField,+ createMockNormalizedField,+} from "metabase-types/api/mocks";import { canIndexField } from "./utils";@@ -14,7 +18,10 @@ const createModelWithResultMetadata = (fields: FieldAPI[]) => {describe("Entities > model-indexes > utils", () => {describe("canIndexField", () => {it("should return true for string field in a model with single integer pk", () => {- const field = createMockField({ name: "foo", base_type: "type/Text" });+ const field = createMockNormalizedField({+ name: "foo",+ base_type: "type/Text",+ });const model = createModelWithResultMetadata([createMockField({ name: "foo", base_type: "type/Text" }),@@ -29,7 +36,10 @@ describe("Entities > model-indexes > utils", () => {});it("should return false for boolean field in a model with single integer pk", () => {- const field = createMockField({ name: "foo", base_type: "type/Boolean" });+ const field = createMockNormalizedField({+ name: "foo",+ base_type: "type/Boolean",+ });const model = createModelWithResultMetadata([createMockField({ name: "foo", base_type: "type/Boolean" }),@@ -44,7 +54,10 @@ describe("Entities > model-indexes > utils", () => {});it("should return false for string field in a model without any pk", () => {- const field = createMockField({ name: "foo", base_type: "type/Text" });+ const field = createMockNormalizedField({+ name: "foo",+ base_type: "type/Text",+ });const model = createModelWithResultMetadata([createMockField({ name: "foo", base_type: "type/Text" }),@@ -55,7 +68,10 @@ describe("Entities > model-indexes > utils", () => {});it("should return false for string field in a model with multiple pks", () => {- const field = createMockField({ name: "foo", base_type: "type/String" });+ const field = createMockNormalizedField({+ name: "foo",+ base_type: "type/String",+ });const model = createModelWithResultMetadata([createMockField({ name: "foo", base_type: "type/Boolean" }),@@ -75,7 +91,10 @@ describe("Entities > model-indexes > utils", () => {});it("should return false for string field in a model with multiple integer pks", () => {- const field = createMockField({ name: "foo", base_type: "type/String" });+ const field = createMockNormalizedField({+ name: "foo",+ base_type: "type/String",+ });const model = createModelWithResultMetadata([createMockField({ name: "foo", base_type: "type/Boolean" }),@@ -95,7 +114,10 @@ describe("Entities > model-indexes > utils", () => {});it("should return false for a model with a string pk", () => {- const field = createMockField({ name: "foo", base_type: "type/Boolean" });+ const field = createMockNormalizedField({+ name: "foo",+ base_type: "type/Boolean",+ });const model = createModelWithResultMetadata([createMockField({ name: "foo", base_type: "type/Boolean" }),diff --git a/frontend/src/metabase/querying/components/DataReference/QuestionPane/QuestionPane.tsx b/frontend/src/metabase/querying/components/DataReference/QuestionPane/QuestionPane.tsxindex dccdd86d2a8..a63ecadaa17 100644--- a/frontend/src/metabase/querying/components/DataReference/QuestionPane/QuestionPane.tsx+++ b/frontend/src/metabase/querying/components/DataReference/QuestionPane/QuestionPane.tsx@@ -27,6 +27,7 @@ import { NodeListTitleText } from "../NodeList";import type {DataReferencePaneProps,DataReferenceQuestionItem,+ UniqueFieldId,} from "../types";import S from "./QuestionPane.module.css";@@ -144,7 +145,9 @@ export const QuestionPane = ({onItemClick({type: "field",id:- typeof field.id === "number" ? field.id : field.getUniqueId(),+ typeof field.id === "number"+ ? field.id+ : (field.getUniqueId() as UniqueFieldId),});}}/>diff --git a/frontend/src/metabase/querying/components/DataReference/TablePane.tsx b/frontend/src/metabase/querying/components/DataReference/TablePane.tsxindex 179df3a54a5..d006d627db9 100644--- a/frontend/src/metabase/querying/components/DataReference/TablePane.tsx+++ b/frontend/src/metabase/querying/components/DataReference/TablePane.tsx@@ -24,7 +24,11 @@ import {NodeListTitleText,} from "./NodeList";import { TableInfoLoader } from "./TableInfoLoader";-import type { DataReferencePaneProps, DataReferenceTableItem } from "./types";+import type {+ DataReferencePaneProps,+ DataReferenceTableItem,+ UniqueFieldId,+} from "./types";export function TablePane({id,@@ -71,7 +75,7 @@ export function TablePane({id:typeof field.id === "number"? field.id- : field.getUniqueId(),+ : (field.getUniqueId() as UniqueFieldId),});}}/>diff --git a/frontend/src/metabase/selectors/metadata.ts b/frontend/src/metabase/selectors/metadata.tsindex 2a2a6e93ca9..a0f7d609f2c 100644--- a/frontend/src/metabase/selectors/metadata.ts+++ b/frontend/src/metabase/selectors/metadata.ts@@ -237,12 +237,7 @@ function createTable(table: NormalizedTable, metadata: Metadata): Table {}function createField(field: NormalizedField, metadata: Metadata): Field {- // We need a way to distinguish field objects that come from the server- // vs. those that are created client-side to handle lossy transformations between- // Field instances and FieldDimension instances.- // There are scenarios where we are failing to convert FieldDimensions back into Fields,- // and as a safeguard we instantiate a new Field that is missing most of its properties.- const instance = new Field({ ...field, _comesFromEndpoint: true });+ const instance = new Field(field);instance.metadata = metadata;return instance;}diff --git a/frontend/src/metabase/utils/formatting/field.ts b/frontend/src/metabase/utils/formatting/field.tsindex c5bf21315fa..8592a46e7e7 100644--- a/frontend/src/metabase/utils/formatting/field.ts+++ b/frontend/src/metabase/utils/formatting/field.ts@@ -1,6 +1,8 @@import type { Field } from "metabase-types/api/field";-export function formatField(field: Field) {+type FormattableField = Pick<Field, "name" | "display_name" | "dimensions">;++export function formatField(field: FormattableField) {if (!field) {return "";}diff --git a/src/metabase/lib/js/metadata.cljc b/src/metabase/lib/js/metadata.cljcindex 84aac114e1c..09126a00bd2 100644--- a/src/metabase/lib/js/metadata.cljc+++ b/src/metabase/lib/js/metadata.cljc@@ -228,8 +228,7 @@(defmethod excluded-keys :field[_object-type]- #{:_comesFromEndpoint- :database+ #{:database:metrics:table})