我想有一个打字类型,它只允许除了它的‘Kind’之外的一个属性,而且它会根据‘Kind’键的值而变化.
我知道这或多或少是在重写JSON已经做的事情,但我对此没有任何发言权.
以下方法可以使用,但在这种情况下,我更愿意使用动态类型:
export interface TitleComponent {
kind: 'title'
title: {
text: string
isSubtitle: boolean
}
}
export interface TextComponent {
kind: 'text'
text: {
text: string
isBordered: boolean
}
}
export interface ImageComponent {
kind: 'image'
image: {
name: string | null
url: string
thumbnailUrl: string | null
altText: string | null
caption: string | null
}
}
export type Component = TitleComponent | TextComponent | ImageComponent
可能的组件Bundle 在一起(还有更多,这只是为了简短):
export interface Components {
title: {
text: string
isSubtitle: boolean
}
text: {
text: string
isBordered: boolean
}
image: {
name: string | null
url: string
thumbnailUrl: string | null
altText: string | null
caption: string | null
}
}
我的打字问题(天真的方法不起作用):
type AvailableKinds = string & keyof Components;
export interface Component {
kind: AvailableKinds;
this['kind']: Components[this['kind']];
}
用法示例:
const t: Component = {
kind: 'title',
title: {
text: 'test',
isSubtitle: false
}
};
这完全可以通过TypeScrip来实现(或者我必须坚持上面的解决方案)吗?