I have the following code:
interface F {
(): string;
a(): number;
}
function f() {
return '3';
}
f['a'] = function () {
return 3;
};
Then I want to assign a function to a variable. I can do it like this:
let z = <F>f; // works
or like this:
let y: F = f; // doesn't work
What's the difference?
T.J. Crowder :
The root issue is that f is just a function, and you're trying to use it as though it were an instance of an interface. (And I think that's fine, it's compatible with the interface, it's just a syntax thing.)\n\nThis is fine:\n\nlet z = <F>f; // works\n\n\n...because it's using a cast to tell TypeScript that although f is just a function as far as TypeScript knows, you know better and it's compatible with the interface F. Then type inference comes into play and assigns the type F to z because the right-hand side of the assignment is of type F.\n\nBut this:\n\nlet y: F = f; // doesn't work\n\n\n...doesn't work because it's declaring y as being type F, and then assigning a function to it. The function isn't of type F, so the assignment fails.",
2017-01-25T18:27:33