javascript - 获取 typescript 默认/初始参数类型以扩展它

标签 javascript typescript graphql-js

我正在处理一些基于函数调用(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/

相关文章:

javascript - Meteor 账号密码只返回_id

javascript - Jquery 在特定父元素后插入行

typescript - 为什么我不能使用常量中的值作为自定义类型定义?

javascript - GraphQL 更新上的 Sequelize 不返回任何内容

javascript - 如何通过串口将数据从网站发送到处理器?

javascript - 两个数字不等于,但它们具有相同的类型和值

javascript - 将值传递给构造函数时使构造函数正常工作的问题

Firebase 和 GraphQL

javascript - 带有 graphql 和 document.toObject() 的 mongodb _id

javascript - 你为什么要把/* 放在你的 jQuery 函数周围?