Home > Back-end >  Override constraint type in generic type (Typescript)
Override constraint type in generic type (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;
}
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

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

type numType=DataType<number>;

Is there any way that i can force helper type to accept any other type than keyof 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