Answer the question
In order to leave comments, you need to log in
Why doesn't it work?
function testFunction<T>(arg: number): T {
return { testField: arg }
}
interface ITest {
testField: number;
}
const x = testFunction<ITest>(5);
Type '{ testField: number; }' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to '{ testField: number; }'.
Answer the question
In order to leave comments, you need to log in
Your return value from the function belongs to a pure type T
that has no type attributes ITest
, which is what the error says. You think that with the help of type arguments you have specified the value returned by the function. That is, you look, as it were, from the outside. But the compiler needs to match the types within the function itself. By doing this, it detects a type mismatch with { testField: number }
type T
.
It is difficult to advise anything, because in such a context it is not clear what you want to achieve.
Generic is not needed here, your function will always return ITest anyway, because TS has structural typing.
And TS swears, since there is no contract on T, and in fact inside the function this is equivalent to unknown
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question