TypeScript A computed property name in a type literal must directly refer to a built-in symbol

后端 未结 2 535
盖世英雄少女心
盖世英雄少女心 2020-12-31 06:37

ERROR in ...component.ts (..,..): A computed property name in a type literal must directly refer to a built- in symbol. ...: Cannot find name \'any\'.

2条回答
  •  离开以前
    2020-12-31 06:45

    I had a similar issue after building. The two issues I faced were with using numbers and or enum values as keys in objects. Just to help those that see this in the future.

    Enums as keys

    export enum MyEnum {
      one = 'stringOne',
      two = 'stringTwo',
    }
    
    export const someMap = {
      [ MyEnum.one ]: 'valueOne',
      [ MyEnum.two ]: 'valueTwo',
    };
    

    This will transpile someMap to a type that look something like...

    export declare const someMap: {
      [ MyEnum.one ]: string;
      [ MyEnum.two ]: string;
    };
    

    Note the keys are still the enum value and not strings, typescript/angular does not like that because it is expecting something like...

    export declare const someMap: {
      [ x: string ]: string;
    };
    

    So two possible fixes are...

    1) Assign explicit type to someMap

    export interface ForceStringType {
      [product: string]: string;
    }
    export const someMap: ForceStringType = {
      [ MyEnum.one ]: 'valueOne',
      [ MyEnum.two ]: 'valueTwo',
    };
    

    2) Assign string type to keys of someMap

    export const someMap: ForceStringType = {
      [ MyEnum.one as string ]: 'valueOne',
      [ MyEnum.two as string ]: 'valueTwo',
    };
    

    Numbers as keys

    const CONSTANT_ONE = 123;
    const CONSTANT_TWO = 321;
    
    export const someMap = {
      [ CONSTANT_ONE ]: 'valueOne',
      [ CONSTANT_TWO ]: 'valueTwo',
    };
    

    This will transpile someMap to a type that look something like...

    export declare const someMap: {
      [ CONSTANT_ONE ]: string;
      [ CONSTANT_TWO ]: string;
    };
    

    Note the keys are still the constant/number value and not strings, typescript/angular is again expecting something like...

    export declare const someMap: {
      [ x: string ]: string;
    };
    

    So one possible fix is...

    Interpolate number as string for each key of someMap

    export declare const someMap: {
      [ `${CONSTANT_ONE}` ]: string;
      [ `${CONSTANT_TWO}` ]: string;
    };
    

    Note: Accessing a value from someMap with the constant/number as a key should not matter as typescript will coerce it to a string anyway, but probably best for overall consistency.

    const valueOne: string = someMap[ CONSTANT_ONE ];
    // vs
    const valueOne: string = someMap[ `${CONSTANT_ONE}` ];
    

提交回复
热议问题