L
L
lightseeker2020-08-13 14:09:12
typescript
lightseeker, 2020-08-13 14:09:12

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

2 answer(s)
T
twoone, 2020-08-13
@twoone

Your return value from the function belongs to a pure type Tthat 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.

D
Dmitry Belyaev, 2020-08-13
@bingo347

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 question

Ask a Question

731 491 924 answers to any question