如何在 Typescript 中编写函数就地解构的类型?

问题描述 投票:0回答:1

用户会将

hisObject
传递给
myFn
。看这个简单的例子:

type HisType = { a:string, b:number };

function myFn( { a:string, b:number } = hisObject): void {
  console.log(a,b);
}

但是我们可以包含

hisObject
的类型为
HisType
以避免错误吗?

如何在 TypeScript 中编写函数就地解构的类型?

typescript destructuring
1个回答
4
投票

没有默认参数:

function myFn({ a, b }: HisType): void {
  console.log(a, b);
}

带有默认参数(

hisObject
指向默认值):

// This exists earlier in the program
const hisObject: HisType = /* ... */;

function myFn({ a, b }: HisType = hisObject): void {
  console.log(a, b);
}
© www.soinside.com 2019 - 2024. All rights reserved.