![](/img/trans.png)
[英]TypeScript - A computed property name must be of type 'string', 'number', 'symbol', or 'any'
[英]Typescript error: A computed property name must be of type 'string', 'number', 'symbol', or 'any'
这是我当前的代码:
interface sizes {
[key: string]: Partial<CSSStyleDeclaration>[];
}
export const useStyleBlocks = (
resolution = 'large',
blocks = [{}]
): Partial<CSSStyleDeclaration>[] => {
const starterBlock = [] as Partial<CSSStyleDeclaration>[];
const handleBlocks = (key: sizes): Partial<CSSStyleDeclaration>[] => {
for (let i = 0; i < blocks.length; i++) {
// the error comes from this line exactly on [key]
// A computed property name must be of type 'string', 'number', 'symbol', or 'any'
starterBlock.push({ [key]: blocks });
}
return starterBlock;
};
switch (resolution) {
case 'small':
// then here i get another error
// Argument of type 'string' is not assignable to parameter of type 'sizes'
handleBlocks('small');
break;
default:
handleBlocks({});
break;
}
return starterBlock;
};
关于错误的解释在上面的代码中进行了注释^
有任何想法吗?
更新:
如果我将函数handleBlocks
更改为:
const handleBlocks = (key: string): Partial<CSSStyleDeclaration>[] => {
for (let i = 0; i < blocks.length; i++) {
/* HERE I GET A NEW ERROR:
Argument of type '{ [x: string]: {}[]; }' is not assignable to parameter of type 'Partial<CSSStyleDeclaration>'.
Index signatures are incompatible.
Type '{}[]' is not assignable to type 'string'.ts(2345) */
starterBlock.push({ [key]: blocks });
}
return starterBlock;
};
有了这个改变, switch
语句上的错误就消失了。
这一行:
const handleBlocks = (key: sizes): Partial<CSSStyleDeclaration>[] => {
是说, handleBlocks
想要类型的参数sizes
,这是一个对象的接口,但是当你调用handleBlocks
,你传递一个字符串(“小”)。
然后,它抱怨您试图将对象类型用于计算属性名称,因为key
的类型是sizes
,它是一个对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.