给定不一致类型的数组。这可以用于动态渲染HTML元素,例如。
interface IElement {
type: 'button' | 'input'
content: Button & Input
}
interface Button {
text?: string;
backgroundColor?: string;
}
interface Input {
value?: string;
placeholder?: string;
}
const elements: IElement[] = [
{
type: 'button',
content: {
text: 'Start',
backgroundColor: 'salmon'
}
},
{
type: 'input',
content: {
value: 'phone',
placeholder: 'Phone'
}
}
]
const newElement = elements.map(element => element.content.backgroundColor)
除了联合类型,还有没有其他方法可以根据 type
属性正确地进行类型转换?
content
的类型。在你的通用答案中,你被迫定义content: T1 & T2
,然后将所有实际内容属性设置为可选项。这不是类型安全的做法。 - ccartonIElement
没有任何作用,可能会引起混淆。 - Aluan Haddad