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