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)
所以两个可能的修复是......
someMapexport interface ForceStringType {
[product: string]: string;
}
export const someMap: ForceStringType = {
[ MyEnum.one ]: 'valueOne',
[ MyEnum.two ]: 'valueTwo',
};
Run Code Online (Sandbox Code Playgroud)
string类型的键someMapexport 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)
所以一种可能的解决方法是......
someMapexport declare const someMap: {
[ `${CONSTANT_ONE}` ]: string;
[ `${CONSTANT_TWO}` ]: string;
};
Run Code Online (Sandbox Code Playgroud)
注意:
someMap使用常量/数字作为键访问值应该无关紧要,因为打字稿无论如何都会将其强制为字符串,但可能最适合整体一致性。Run Code Online (Sandbox Code Playgroud)const valueOne: string = someMap[ CONSTANT_ONE ]; // vs const valueOne: string = someMap[ `${CONSTANT_ONE}` ];
zur*_*fyx 10
需要计算值的标识名称:
foo: { [bar: string]: string };
Run Code Online (Sandbox Code Playgroud)
在目前公认的答案是行不通的,如果密钥类型来自于通用的。为此,您需要使用in运算符:
type WithKey<K extends string | number | symbol> = {
[k in K]: boolean
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8532 次 |
| 最近记录: |