简体   繁体   English

如何在 Typescript 中为 function 就地解构编写类型?

[英]How do you write the types for a function in-place destructuring in Typescript?

A user will pass an hisObject to myFn .用户会将hisObject传递给myFn See this simple example:看这个简单的例子:

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

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

But could can we include that hisObject is of type HisType to avoid errors?但是我们可以包括hisObject的类型是HisType以避免错误吗?

Without default argument:没有默认参数:

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

With default argument ( hisObject points to the default value):使用默认参数( hisObject指向默认值):

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM