【问题标题】:Typescript add typing on Fn's parametrs with destructuring+restTypescript 使用解构+休息在 Fans 参数上添加类型
【发布时间】:2021-07-24 02:09:44
【问题描述】:

问题

您好,尝试学习一些打字稿的打字,但在尝试在打字稿中添加打字时遇到了一些问题:

我不确定如何在 Typescript 中将其转换为强类型。

const omit = (prop: P, { [prop]: _, ...rest}) => rest;

  • 所以问题是如何在第二个参数中为解构对象添加类型

我尝试了什么

这是我认为它应该看起来但不起作用的样子:

const omit = <P = string, R>(prop: P, { [prop]: _, ...rest } : {[prop: string], rest: R }): R => rest;

const omit = <P = string, O, R = Omit<O,P>>(prop: P, { [prop]: _, ...rest } : {[prop: string]: O[P], rest: R }): R => rest;

const omit = <P = string, R>(prop: P, { [prop]: _, ...rest } : {[prop]: P, rest: R }): R => rest;

【问题讨论】:

  • 您有严重的语法错误,难以理解您要完成的工作。我建议您 1) 提供一个简单的 JS 示例,说明您尝试在 TypeScript 中建模的内容,2) 学习 TypeScript 教程。
  • 不确定上面的例子有什么严重的,但我有红色的文档。很抱歉让您感到困惑,我已经说过,我展示的下面的代码块是行不通的。

标签: typescript typescript-typings


【解决方案1】:

这实际上写起来相当简单。您在使用泛型方面走在了正确的轨道上,但是您试图根据如何分解第二个参数来计算函数的结果来表达第二个参数的类型,这不是这里要走的路。

相反,允许第二个参数采用任何类型,方法是声明一个不受约束的泛型,并将第一个参数的类型指定为任何属性,即泛型实例化时使用的任何类型的键,即无论第二个参数的类型是什么。

const omit = <O, P extends keyof O>(prop: P, { [prop]: _, ...rest }: O): Omit<O, P> => rest;
const o = { a : 1, b: 2 };
const r = omit('a', o);

Playground Link

请注意,函数的返回类型将被正确推断为Omit&lt;O, P&gt;,无需指定。

const omit = <O, P extends keyof O>(prop: P, { [prop]: _, ...rest }: O) => rest;

【讨论】:

  • 感谢您的回答,所以我把事情复杂化了,不认为打字稿能够代表这种复杂的形式。这应该是简单的方法! ?
猜你喜欢
  • 2019-04-19
  • 2017-07-08
  • 2020-03-27
  • 1970-01-01
  • 1970-01-01
  • 2019-01-29
  • 1970-01-01
  • 2018-12-25
  • 2020-12-11
相关资源
最近更新 更多