Typescript:定义键列表的类型

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

Typescript: define types for list of keys

问题

我有一个频道列表,类似于:

type Channels = 'Channel1' | 'Channel2' | ....

每个频道都有自己的类型,所以我正在使用这段代码:

type BaseTypes = {[key in Channels]: object};
interface ChannelTypes extends BaseTypes {
    Channel1: {/* 定义所需数据 */},
    Channel2: {/* 定义所需数据 */},
}

我想找到一种方法,当我向频道添加一个值时,强制我更新 ChannelTypes,并拒绝在 Channels 中未定义的任何键在 ChannelTypes 中。

英文:

I have a list of channels like:

type Channels = 'Channel1' | 'Channel2' | ....

and each channel has its own type, so I am using this code:

type BaseTypes = {[key in Channels]: object};
interface ChannelTypes extends BaseTypes {
    Channel1: {/* define required data*/},
    Channel2: {/* define required data*/},
}

I want to find a way when I add a value to channels to force me to update ChannelTypes, and reject any key in ChannelTypes not defined in Channels

答案1

得分: 0

You can use mapped types and lookup types. First define a type with a list of channels as you did:

type Channels = 'Channel1' | 'Channel2';

Next, define a type that maps channel types to their data, for example:

type ChannelToData = {
  Channel1: string;
  Channel2: number;
};

And finally, define a type:

type ChannelTypes = {
    [Channel in Channels]: ChannelToData[Channel];
};

With this approach, if you add a new type to the union Channels, TypeScript will force you to define a specific data type for it in the type ChannelToData.

英文:

You can use mapped types and lookup types. First define type with list of channels as you did:

type Channels = 'Channel1' | 'Channel2';

Next define type which maps channel type to its data, for example:

type ChannelToData = {
  Channel1: string;
  Channel2: number;
};

And finally define type:

type ChannelTypes = {
    [Channel in Channels]: ChannelToData[Channel];
};

With this approach, if you add new type to union Channels, TypeScript forces you to define specific data type for it in type ChannelToData.

Playground

huangapple
  • 本文由 发表于 2023年5月11日 17:50:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76226314.html
匿名

发表评论

匿名网友

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

确定