![](/img/trans.png)
[英]How to define a function's argument type as one of the keys (or properties) of an interface
[英]How to define type for all properties in an interface?
我正在定義一個在i18n應用程序中提供字符串的接口:
interface ILocaleStringsProvider {
'foo': string
'bar': string
'baz': string
'blablabla': string
// hundreds of string properties here...
}
我不想重復: string
很多次。
有沒有一種方法可以一次定義所有屬性的類型?
您可以使用Record<K extends string, T>
類型。 如果不同字段的類型不同,則可以使用聯合類型:
type ILocaleStringsProvider =
Record<'foo'|'bar'|'baz'|'blablabla',string> &
Record<'foo2'|'bar2'|'baz2'|'blablabla2',number>;
您可以在以下位置使用Index,Union和:
type ILocaleStringsProvider = {
[i in 'foo' | 'bar' | 'baz' | 'blablabla']: string
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.