[英]How to define type for all properties in an interface?
I'm defining an interface which provides strings in i18n application: 我正在定义一个在i18n应用程序中提供字符串的接口:
interface ILocaleStringsProvider {
'foo': string
'bar': string
'baz': string
'blablabla': string
// hundreds of string properties here...
}
I don't like to repeat : string
many times. 我不想重复
: string
很多次。
Is there a way to define the type of all properties at a time? 有没有一种方法可以一次定义所有属性的类型?
You could use the Record<K extends string, T>
type. 您可以使用
Record<K extends string, T>
类型。 If you have different types for different fields you can use union types: 如果不同字段的类型不同,则可以使用联合类型:
type ILocaleStringsProvider =
Record<'foo'|'bar'|'baz'|'blablabla',string> &
Record<'foo2'|'bar2'|'baz2'|'blablabla2',number>;
You could use Index, Union and in: 您可以在以下位置使用Index,Union和:
type ILocaleStringsProvider = {
[i in 'foo' | 'bar' | 'baz' | 'blablabla']: string
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.