TypeScript类型文字中的计算属性名称必须直接引用内置符号

zur*_*fyx 3 typescript

ERROR in ... component.ts(..,..):类型文字中的计算属性名称必须直接引用内置符号.......:找不到名字'any'.

我期待一个包含其他字符串的字符串的对象,即:

{ abc: 'xyz' }
Run Code Online (Sandbox Code Playgroud)

我做了什么:

foo: { [string]: string };
Run Code Online (Sandbox Code Playgroud)

Nic*_*yme 26

构建后我遇到了类似的问题。我面临的两个问题是使用数字和/或枚举值作为对象中的键。只是为了帮助那些将来看到这一点的人。

枚举作为键

export enum MyEnum {
  one = 'stringOne',
  two = 'stringTwo',
}

export const someMap = {
  [ MyEnum.one ]: 'valueOne',
  [ MyEnum.two ]: 'valueTwo',
};
Run Code Online (Sandbox Code Playgroud)

这将转换someMap为一种看起来像......

export declare const someMap: {
  [ MyEnum.one ]: string;
  [ MyEnum.two ]: string;
};
Run Code Online (Sandbox Code Playgroud)

请注意,键仍然是枚举值而不是字符串,打字稿/角度不喜欢那样,因为它期待类似......

export declare const someMap: {
  [ x: string ]: string;
};
Run Code Online (Sandbox Code Playgroud)

所以两个可能的修复是......

1) 将显式类型分配给 someMap

export interface ForceStringType {
  [product: string]: string;
}
export const someMap: ForceStringType = {
  [ MyEnum.one ]: 'valueOne',
  [ MyEnum.two ]: 'valueTwo',
};
Run Code Online (Sandbox Code Playgroud)

2)分配string类型的键someMap

export const someMap: ForceStringType = {
  [ MyEnum.one as string ]: 'valueOne',
  [ MyEnum.two as string ]: 'valueTwo',
};
Run Code Online (Sandbox Code Playgroud)

数字作为键

const CONSTANT_ONE = 123;
const CONSTANT_TWO = 321;

export const someMap = {
  [ CONSTANT_ONE ]: 'valueOne',
  [ CONSTANT_TWO ]: 'valueTwo',
};
Run Code Online (Sandbox Code Playgroud)

这将转换someMap为一种看起来像......

export declare const someMap: {
  [ CONSTANT_ONE ]: string;
  [ CONSTANT_TWO ]: string;
};
Run Code Online (Sandbox Code Playgroud)

请注意,键仍然是常量/数字值而不是字符串,打字稿/角度再次期待类似...

export declare const someMap: {
  [ x: string ]: string;
};
Run Code Online (Sandbox Code Playgroud)

所以一种可能的解决方法是......

为每个键插入数字作为字符串 someMap

export declare const someMap: {
  [ `${CONSTANT_ONE}` ]: string;
  [ `${CONSTANT_TWO}` ]: string;
};
Run Code Online (Sandbox Code Playgroud)

注意:someMap使用常量/数字作为键访问值应该无关紧要,因为打字稿无论如何都会将其强制为字符串,但可能最适合整体一致性。

const valueOne: string = someMap[ CONSTANT_ONE ];
// vs
const valueOne: string = someMap[ `${CONSTANT_ONE}` ];
Run Code Online (Sandbox Code Playgroud)


zur*_*fyx 10

需要计算值的标识名称:

foo: { [bar: string]: string };
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您的密钥类型来自泛型,则需要使用不同的解决方案:/sf/answers/4619780301/ (2认同)

Eri*_*ric 8

目前公认的答案是行不通的,如果密钥类型来自于通用的。为此,您需要使用in运算符:

type WithKey<K extends string | number | symbol> = {
    [k in K]: boolean
}
Run Code Online (Sandbox Code Playgroud)

信用在这里