我正在处理一些基于函数调用(GraphQL Nexus 东西)自动生成类型提示的代码。
然后,在它的一个函数中,它需要一个基于这些自动生成属性的匿名类型:
export const Item = {
isTypeOf(data) { // data's type is an anonymous type, here it would be '{ name: string }'
...
}
definition(t) {
t.string('name')
}
}
然而,这个data
参数可能包含比函数调用定义的变量更多的变量。就我而言,我需要访问 kind
属性(property),但我无法拨打 t._type_
功能,因为它会产生不希望的副作用。我也不能只将类型传递为
{ kind: string }
自 isTypeOf
type 期望它至少在其参数上具有所有定义的属性。我可以用
{ name: string, kind: string }
在这个例子中,但我的实际代码包含更复杂的对象,我将失去自动生成的输入内容的所有好处。有什么方法可以让我使用匿名类型在线扩展参数吗?我在想类似
initial
的事情或 default
关键字来获取参数自己的类型,并像这样使用它:isTypeOf(data: initial & { kind: string })
isTypeOf(data: default & { kind: string })
最佳答案
Typescript 不关心传递给函数的对象中的其他键(除非在参数列表中创建)。
如果您只想接受具有给定属性和 的对象不回它,使用 isTypeOf
的定义.
如果您需要返回相同的类型并可能扩展它,请使用 definition
的定义.
export const Item = {
isTypeOf(data: { kind: string }): boolean {
return data.kind == '...';
},
definition<T extends { string: (key: string): void }>(t): T & { defined: true } {
t.string('name');
(t as T & { defined: true }).defined = true;
return t;
},
};
const myType = {
kind: 'hello',
name: 'World',
string(key: string): {},
};
Item.isTypeOf(myType); // OK
Item.isTypeOf({ kind: 'hello', name: 'World' }); // Not OK
Item.definition(myType); // OK
Item.definition({ string(key: string): {} }); // OK
关于javascript - 获取 typescript 默认/初始参数类型以扩展它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69646747/