Home > Software engineering >  Overriding the constraint type of the generic type in typescript
Overriding the constraint type of the generic type in typescript

Time:01-27

I have created a generic type helper called DataType, which accepts a parameter T that is constrained to the keyof MyObject type. If the key is present in MyObject,DataType will return the property type of MyObject; otherwise, it will return T itself.

interface MyObject {
  foo: string;
  bar: boolean;
}
export type DataType<T extends keyof MyObject> = T extends keyof MyObject
  ?  MyObject[T] 
  : T;

Now if I pass any key of MyObject, it will return the corresponding type:

type StrType=DataType<'foo'>; // data type is string

But if I pass a data type other than a string to this helper, I am getting Type 'type' does not satisfy the constraint '"foo"':

type numType=DataType<number>;

How to not constrain the type but still have IntelliSense prompt for the key of MyObject?

CodePudding user response:

You really don't want to constrain T; it can be anything, even the unknown type. That can be accomplished by just leaving it as type DataType<T> = ... without a constraint on the T.

interface MyObject {
  foo: string;
  bar: boolean;
}

type DataType<T> =
  T extends keyof MyObject ? MyObject[T] : T;

type StrType = DataType<'foo'>; // string
type NumType = DataType<number>; // number

But if you do that, you will lose IntelliSense hints suggesting the string literal type members of keyof MyObject:

// type BooType = DataType<'⃒'> 
// ----------------------> ^^ <---
// IntelliSense prompts here with NOTHING            
  • Related