I've come across the following Typescript idiom quite a bit in an application.
interface something {
comment: string;
}
const f = <something>({ data: result }) => result.comment;
console.log(f({ data: { comment: "Hi Mom"} }));
which produces "Hi Mom" on the console as expected.
I've got two basic questions:
result
and cast it as a something
", but I don't understand how this accomplishes that. How is result
being bound appropriately in the function call?something
is a shadowed name. As far as I can see, it's a typecast, and I don't see how a typecast defines a name at all, let alone one that's shadowed.Can someone enlighten me?
Take the value of whatever the data field of the object that I pass you contains, call it result
Is correct, it's called destructuring assignment.
and cast it as a something
Apparently, in this example, it's just a mistake, it does nothing there. These are called Generic types. I can only say that example should look like that, so it uses generics in the right way:
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
That's right because something
is was defined as an interface, and as a generic type, so tslist complains