[英]es6 destructuring params in a function with typescript
I still want to use destructuring because visually it helps in calling a function. But I have a problem doing it in a function params:我仍然想使用解构,因为在视觉上它有助于调用 function。但我在 function 参数中遇到问题:
const t = ({id, name}: {number, string}) => `id: ${id} name:${name}`
another failed approach where I try to avoid putting all types of the param in one line but use an interface:另一种失败的方法,我试图避免将所有类型的参数放在一行中,而是使用一个接口:
interface tParams {
id: number,
name: string
}
const t = ({id, name} as tParams) => `id: ${id} name:${name}`
You can either do it this way:您可以这样做:
const t = ({id, name}: {id: number, name: string}) => `id: ${id} name:${name}`
or this way:或者这样:
interface tParams {
id: number,
name: string
}
const t = ({id, name}: tParams) => `id: ${id} name:${name}`
Destructure works on any object type. Destructure 适用于任何 object 类型。 So if your object definition is correct destructure will work.
因此,如果您的 object 定义正确,则解构将起作用。 Here the person is on an object which consists id and name.
这里的人在 object 上,它由 id 和 name 组成。 So both function are correct
所以function都是正确的
interface Person {
id?:number;
name: string;
}
const t = (person: Person) => `id: ${person.id} name:${person.name}`
// Equivalent to
const t2 = ({id, name}: Person) => `id: ${id} name:${name}`
as
is use for casting as
铸造
class Employee {
name:string;
salary: number;
}
const emp = new Employee()
console.log(emp.id) //Error here since emp does not have id.
console.log((emp as Person).id) //NO error
Edit your answer to this should fix it:编辑你的答案应该解决它:
const t = ({id, name}: {id: number, name: string}) => `id: ${id} name:${name}`
Hopefully, the stuff below helps and gives you an idea.希望下面的内容对您有所帮助并给您一个想法。
const t = ({id, name}) => `id: ${id} name:${name}`;
interface tParams {
id: number,
name: string
}
const t2 = ({id, name} : tParams) => `id: ${id} name:${name}`;
//testing code below
let tParamsObject: tParams = {
id: 123,
name: "James"
};
console.log (t(tParamsObject));
console.log (t2(tParamsObject));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.