Reputation: 105517
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?
Upvotes: 3
Views: 56
Reputation: 164287
This is how I would do it:
interface F {
(): string;
a(): number;
}
function f() {
return '3';
}
let f1 = f as F;
f1.a = function () {
return 3;
};
Using as F
is equivalent to <F>
and it's called type assertion.
Yes, you can define f
to be of type F
like so:
let f3 = function() {
return "3";
} as F;
f.a = function () {
return 3;
};
Or using an arrow function:
let f = (() => {
return "3";
}) as F;
Upvotes: 1
Reputation: 1074959
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.)
This is fine:
let z = <F>f; // works
...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
.
But this:
let y: F = f; // doesn't work
...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.
Upvotes: 3