Relative Content

Tag Archive for typescriptgenericstypescript-generics

TS doesn’t match exact type to generic?

type Input = ‘a’ | ‘b’; type ResultOf<T extends Input> = T extends ‘a’ ? ‘A’ : ‘B’; function foo<T extends Input>(input: T): ResultOf<T> { return input === ‘a’ ? ‘A’ : ‘B’; } The code above errors with error TS2322: Type ‘”A” | “B”‘ is not assignable to type ‘ResultOf<T>’., but why? typescript generics […]

Enforcing Same Generic Types in TypeScript

I’m having trouble enforcing the same generic type for two instances of TValidationAdapter. Without an explicit field (_typeEnforcer) using the generic type, TypeScript isn’t complaining when the types differ (see video).

Generic Function which guarantees a key of specific type

I’m trying to implement a generic sort, which does 2 things.
It takes an array of type T, that must have atleast one key with the specified type(string in this example), and an key from T without specifying which key it in the function body is(imagine multiple properties with string values, i should be able to pass any of them). However I can’t quite get right. Either I end up with a type missmatch on the callers side(as example is showing). Or i end up with a function body that is of type any, such is the case if i replace [name: string]: name with[name: string]: any. Or I’am forced to name the specific key that i want to use for sorting(which I don’t really wanna do as that removes the reusability). as is the case for T extends {name: string}