英文:
Is is possible to create a new TypeScript interface of array types from an existing interface of non-array types?
问题
我有类似这样的:
type Thunk = 'uh' | 'um' | 'dunno mate';
interface Whatever {
meh: Thunk;
}
那就没问题,兄弟。但后来我需要这个:
interface LoadsOfWhatever {
meh: Thunk[];
}
有没有办法从 Whatever
扩展/选择等等,还是只能按字面意思创建?
英文:
I have [something akin to] this:
type Thunk = 'uh' | 'um' | 'dunno mate';
interface Whatever {
meh: Thunk;
}
And that's all good my bro. But then later I need this:
interface LoadsOfWhatever {
meh: Thunk[];
}
Is there a way to extend/Pick/etc it from Whatever
or will this just need to be literally created?
答案1
得分: 1
这可以通过mapped types来完成。它们允许您从旧类型计算出一个新类型,对每个属性应用一些转换。下面是将每个属性转换为数组的示例:
type Thunk = 'uh' | 'um' | 'dunno mate';
interface Whatever {
meh: Thunk;
}
type LoadsOfWhatever = {
[key in keyof Whatever]: Whatever[key][];
}
显然,如果您只有一个meh
属性,这比原始代码更冗长。但如果Whatever
有50个属性,您无需更改LoadsOfWhatever
;它会将所有50个属性转换为数组。
英文:
This can be done with mapped types. These let you calculate a new type from an old one, applying some transformation to every property. Here's how it looks to turn every property into an array:
type Thunk = 'uh' | 'um' | 'dunno mate';
interface Whatever {
meh: Thunk;
}
type LoadsOfWhatever = {
[key in keyof Whatever]: Whatever[key][];
}
Obviously it's wordier than the original code if all you have is the one meh
property. But if Whatever
had 50 properties, you wouldn't need to change LoadsOfWhatever
; it would turn all 50 properties into arrays
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论