假设给定数据
const dataA = {
name: "John",
age: 25,
attributes: {specificA: "hello", specificA2: 14, nonspecific:"Well"},
}
const dataB = {
name: "Lisa",
age: 38,
attributes: {specificB: "hello", someMoreSpecificStuff: true, nonspecific:"Hope this"},
}
const dataC = {
name: "Peter",
age: 60,
attributes: {specificC: "hello", couldBeAnyName: "Oh My", nonspecific:"makes sense"},
}
我的一些组件只会访问一般信息 ( name, age)
有些其他组件只会访问一般信息,但也会访问在键相同但值不同的属性中共享的一般信息 ( attributes.nonspecific) 有些组件只能工作数据类型之一。
到目前为止,我想出的是:
const dataA: MyDataType<A> = {
name: "John",
age: 25,
attributes: {specificA: "hello", specificA2: 14, nonspecific:"Well"},
}
const dataB: MyDataType<B> = {
name: "Lisa",
age: 38,
attributes: {specificB: "hello", someMoreSpecificStuff: true, nonspecific:"Hope this"},
}
const dataC:MyDataType<C> = {
name: "Peter",
age: 60,
attributes: {couldBeAnything: "Oh My", nonspecific:"makes sense"},
}
type MyDataType<T extends A | B | C> = {
name: string;
age: number;
attributes: T
}
type A = {
specificA: string;
specificA2: number;
nonspecific: string;
}
type B = {
specificB: string;
someMoreSpecificStuff: true;
nonspecific: string;
}
type C = {
couldBeAnything: string;
nonspecific: string;
}
这很好用,但是如果我现在想要一个组件使用这些数据类型中的任何一种,我必须像这样键入它:
interface ForMyGeneralComponent{
data: MyDataType<A | B | C>
}
我想写的是
interface ForMyGeneralComponent{
data: MyDataType<GenericType>
}
并在某处声明,GenericType或.ABC
你为什么问?想象一下,这些属性可以由多达 30 种不同的类型组成。如果我必须在任何地方输入它们,这会大大降低可读性。而且我猜我很懒?