typescript - 解构函数参数对象并 ...rest

标签 typescript

我想编写一个函数,它接受一个对象参数并将所有剩余参数捕获到一个变量中。目标是允许函数接收命名参数(而不是位置参数),其中一些是可选的,并在函数中设置默认值。 所以,在伪代码中是这样的:

interface IMyProps {
  a: string
  b?: number
}

const myfun1 = (p: {a: string, b?:number, ...rest}) => {
  const {a, b = 'hello'} = p;
}

在 Typescript 2.0 中实现此目标的最佳方法是什么?

最佳答案

您可以直接在函数参数中使用解构赋值:

interface IMyType { 
    a: number;
    b: number;
    c: number;
    d: number;
    [k: string]: number; // use this if you don't know the name of the properties in 'rest'
}

const obj: IMyType = { a: 1, b: 2, c: 3, d: 4 }

// Normal destructuring
const { a, b, ...rest } = obj;
console.log(rest); // {c: 3, d: 4}

// Directly in function arguments
const fn = ({ a, b, ...rest }: IMyType) => { console.log(rest); }

console.log(fn(obj)); // {c: 3, d: 4}

关于typescript - 解构函数参数对象并 ...rest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50288205/

相关文章:

typescript - 提供/注入(inject)和更改注入(inject)变量

html - 带有 X 右上角的 Angular 8 Material 对话框关闭按钮

背景图像上的 Angular (负载)

json - 将日期从 JSON 反序列化为 Typescript 中的日期

javascript - 如何将组件注入(inject)到Angular2中的div选择器中

angular - 为 Angular 应用程序设计

javascript - 使用 rxjs subject 在 Angular 7 中显示和隐藏组件

typescript - 类型错误 : null value in column violates not-null: allow null values ​in a fk

javascript - Angular 2,(更改)事件未在 Bootstrap 复选框上触发

typescript - 类定义的双重断言