[英]write an object with keys and array typescript
I am writing the following in typescript and see the following error 我在打字稿中写以下内容,并看到以下错误
const WEEKDAYS_SHORT = {
en: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
de: ['S', 'M', 'D', 'M', 'D', 'F', 'S'],
};
<StyledDayPicker weekdaysShort={WEEKDAYS_SHORT[language]} />
Type 'string[]' is not assignable to type '[string, string, string, string, string, string, string]'.
类型'string []'不能分配给类型'[string,string,string,string,string,string,string,string]'。 Property '0' is missing in type 'string[]'.
类型'string []'中缺少属性'0'。 [2322]
[2322]
I have tried the following which is giving me an error. 我尝试了以下操作,这给了我一个错误。
const WEEKDAYS_SHORT: string[] = {
en: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
de: ['S', 'M', 'D', 'M', 'D', 'F', 'S'],
};
weekdaysShort
expects a string tuple of length 7. By default typescript infers arrays of fir array literals. weekdaysShort
期望使用长度为7的字符串元组。默认情况下,typescript会推断fir数组文字的数组。 The simple solution is to usa an extra function to help inference along: 一个简单的解决方案是为美国提供一个额外的功能来帮助推断:
const stringTuple = <T extends string[]>(...a: T) => a;
const WEEKDAYS_SHORT = {
en: stringTuple('S', 'M', 'T', 'W', 'T', 'F', 'S'),
de: stringTuple('S', 'M', 'D', 'M', 'D', 'F', 'S')
};
Or you can use a type assertion: 或者,您可以使用类型断言:
type Tuple7 = [string,string,string,string,string,string,string]
const WEEKDAYS_SHORT = {
en: ['S', 'M', 'T', 'W', 'T', 'F', 'S'] as Tuple7,
de: ['S', 'M', 'D', 'M', 'D', 'F', 'S'] as Tuple7,
};
Or in typescript 3.4 (unreleased at this time) you can assert as const
to make the compiler infer a readonly tuple: 或在打字稿3.4中(此时尚未发布),您可以断言
as const
以使编译器推断出一个只读元组:
const WEEKDAYS_SHORT = {
en: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
de: ['S', 'M', 'D', 'M', 'D', 'F', 'S'],
} as const;
Also depending on your compiler setting, and the language
should be 'en' | 'de'
也取决于您的编译器设置,并且
language
应为'en' | 'de'
'en' | 'de'
for indexing to work. 'en' | 'de'
用于索引工作。
Your variable should be defined as such: 您的变量应这样定义:
const WEEKDAYS_SHORT: { [prop: string]: string[] } = {
en: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
de: ['S', 'M', 'D', 'M', 'D', 'F', 'S'],
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.