我有以下类型:
type MyType = {
foo: string;
bar: string;
}[];
如何向该对象添加新属性?
例如:添加{ fooBar: string }
到MyType
所以结果是:
type MyType = {
foo: string;
bar: string;
fooBar: string;
}[];
我能做的最好的就是这个。它有效,但它很麻烦,我想可以使用更优雅的东西
type Solution = Array<
MyType extends Array<infer Item> ? Item & { fooBar: string } : never
>;
谢谢 =)
您可以通过使用 索引数组类型来获取内部数组项类型来做到这一点number
。之后,在数组项类型上创建与您希望成为的新事物的交集。最后,只需使用新创建的项目类型创建一个新的数组类型:
type MyType = {
foo: string;
bar: string;
}[];
type MyBetterType = (MyType[number] & { fooBar: string; })[];
// ^? ({ foo: string; bar: string; } & { fooBar: string; })[]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句