打字稿占位符通用 [英] Typescript Placeholder Generic
问题描述
假设给定数据
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"},
}
我的某些组件将仅访问常规信息(名称
,年龄
)
其他一些人将不仅访问常规信息,而且访问键相同但属性值不相同的属性中共享的常规信息( attributes.nonspecific
)某些组件只能使用一种数据类型.
Some of my components will only access the general information (name
, age
)
Some others will only access the general information, but also the general information that is shared in properties whose keys are the same, but the values are not (attributes.nonspecific
)
Some components will work only one of the data types.
到目前为止,我想到的是:
What I came up so far is this:
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;
}
这很好用,但是如果我现在想要一个组件使用这些数据类型中的任何一种,我必须像这样输入它:
This works fine, but if I now want a component to work with any of these data types, I have to type it like this:
interface ForMyGeneralComponent{
data: MyDataType<A | B | C>
}
我想写的是
interface ForMyGeneralComponent{
data: MyDataType<GenericType>
}
并在某处声明 GenericType
是 A
, B
或 C
.
为什么问?想象一下,这些属性可以由30种不同的类型组成.如果必须在任何地方键入它们,这将大大降低可读性.而且我猜我也很懒?
Why you ask? Imagine these attributes can be made of up 30 different types. If I have to type them out everywhere, this decreases readability by a lot. And also I am lazy I guess?
打字稿操场 >
推荐答案
不确定,如果我了解您的用例.
也许您只想为所有属性引入一种新类型,例如
Not sure, if I understood your use-case.
Maybe you just want to introduce a new type for all your attributes e.g.
type MyAttributes = A | B | C;
type MyDataType<T extends MyAttributes> = {
name: string;
age: number;
attributes: T
}
interface ForMyGeneralComponent{
data: MyDataType<MyAttributes>
}
这篇关于打字稿占位符通用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!