Is is possible to create a new TypeScript interface of array types from an existing interface of non-array types?

huangapple go评论126阅读模式
英文:

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个属性转换为数组。

Playground Link

英文:

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

Playground Link

huangapple
  • 本文由 发表于 2023年3月7日 19:37:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75661479.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定