英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论