You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Expected behavior:
TS should not allow us to use a value instead of a type as argument to Generic (it is a type error)
(e.g - see code below - IType<E.a> should error. Only IType<E> is correct for E.a is not a type but a value of type E)
Actual behavior:
TS treats value of an enum like a type when fed to Generic. It results in type inference problems (see the example below)
Code
enumE{a='a',b='b',}interfaceIType<T>{type: T}interfaceIArrayA{listOfTypeA: Array<IType<E.a>>}interfaceIArrayB{listOfTypeB: Array<IType<E.b>>}consta: IArrayA={listOfTypeA: [{type: E.a}],}constb: IArrayB={listOfTypeB: a.listOfTypeA.map(()=>({type: E.b})),// ERROR: Type 'E' is not assignable to type 'E.b'.}
Error explanation:
Ofc TS's type inference infers that {type: E.b} is of type {type: E} as it should. From that it infers b: {listOfTypeB: Array<{type: E}>}. But we wanted b: {listOfTypeB: Array<{type: E.b}>}.
Workaround: You can override TS's type system and tell it that E.b is of type E.b (although E.b is not a type...) listOfTypeB: a.listOfTypeA.map(() => ({type: E.b as E.b})),
The text was updated successfully, but these errors were encountered:
First, E.a and E.bare types. They represent the two possible singleton values of the enum, and type E is exactly equivalent to E.a | E.b.
The real issue here is that the object literal { type: E.b } in the arrow function passed to map has its type inferred as { type: E } because it isn't contextually typed. We're tracking this exact issue in #11152, so I'm marking this as a duplicate.
@mathiajusth I don’t know if you know this but TypeScript in general has a concept of “literal types”, e.g. ”foo” | “bar” is a type that can only be the string “foo” or the string “bar”—and nothing else. It’s a bit jarring at first but quite useful once you get the hang of utilizing it.
Uh oh!
There was an error while loading. Please reload this page.
TypeScript Version: 3.1.2
Expected behavior:
TS should not allow us to use a value instead of a type as argument to Generic (it is a type error)
(e.g - see code below -
IType<E.a>
should error. OnlyIType<E>
is correct forE.a
is not a type but a value of typeE
)Actual behavior:
TS treats value of an enum like a type when fed to Generic. It results in type inference problems (see the example below)
Code
Error explanation:
Ofc TS's type inference infers that
{type: E.b}
is of type{type: E}
as it should. From that it infersb: {listOfTypeB: Array<{type: E}>}
. But we wantedb: {listOfTypeB: Array<{type: E.b}>}
.Workaround: You can override TS's type system and tell it that E.b is of type E.b (although E.b is not a type...)
listOfTypeB: a.listOfTypeA.map(() => ({type: E.b as E.b})),
The text was updated successfully, but these errors were encountered: