Typescript 箭头函数中的对象字面量参数声明如何工作?
How does an object literal parameter declaration in a Typescript arrow function work?
我在应用程序中经常遇到以下 Typescript 习语。
interface something {
comment: string;
}
const f = <something>({ data: result }) => result.comment;
console.log(f({ data: { comment: "Hi Mom"} }));
按预期在控制台上生成 "Hi Mom"。
我有两个基本问题:
- 实际上,这似乎是在说 "Take the value of whatever the data field of the object that I pass you contains, call it
result
and cast it as a something
",但我不明白这是如何实现的。 result
如何在函数调用中正确绑定?
- 其次,tslint 抱怨
something
是一个影子名称。据我所知,这是一种类型转换,我根本看不出类型转换如何定义名称,更不用说被遮蔽的名称了。
谁能赐教一下?
Take the value of whatever the data field of the object that I pass you contains, call it result
是正确的,它被称为destructuring assignment。
and cast it as a something
显然,在这个例子中,它只是一个错误,它在那里什么都不做。这些被称为 Generic types。我只能说那个例子应该看起来像那样,所以它以正确的方式使用了泛型:
interface something {
data: {
comment: string;
}
}
const f = <T extends something>({ data: result }: T) => result.comment;
console.log(f({ data: { comment: "Hi Mom"} }));
tslint complains that something is a shadowed name
没错,因为 something
被定义为一个接口,并且是一个通用类型,所以 tslist 抱怨
希望已经清楚了:)
我在应用程序中经常遇到以下 Typescript 习语。
interface something {
comment: string;
}
const f = <something>({ data: result }) => result.comment;
console.log(f({ data: { comment: "Hi Mom"} }));
按预期在控制台上生成 "Hi Mom"。
我有两个基本问题:
- 实际上,这似乎是在说 "Take the value of whatever the data field of the object that I pass you contains, call it
result
and cast it as asomething
",但我不明白这是如何实现的。result
如何在函数调用中正确绑定? - 其次,tslint 抱怨
something
是一个影子名称。据我所知,这是一种类型转换,我根本看不出类型转换如何定义名称,更不用说被遮蔽的名称了。
谁能赐教一下?
Take the value of whatever the data field of the object that I pass you contains, call it result
是正确的,它被称为destructuring assignment。
and cast it as a something
显然,在这个例子中,它只是一个错误,它在那里什么都不做。这些被称为 Generic types。我只能说那个例子应该看起来像那样,所以它以正确的方式使用了泛型:
interface something {
data: {
comment: string;
}
}
const f = <T extends something>({ data: result }: T) => result.comment;
console.log(f({ data: { comment: "Hi Mom"} }));
tslint complains that something is a shadowed name
没错,因为 something
被定义为一个接口,并且是一个通用类型,所以 tslist 抱怨
希望已经清楚了:)