Home > database >  Defining a value with type constraints while keeping narrow type of the value in typescript
Defining a value with type constraints while keeping narrow type of the value in typescript

Time:10-06

I would like to declare a value that extends specific type and keeps its narrow type at the same time.

Is there a way to achieve this without calling a function?

const stringRecord : <T extends Record<string, string>>(x: T)=>T= (x) => x;


//Define value that extends Record<string, string> without calling a function 
const abc = stringRecord({
      a: "a",
      b: "b",
      c: "c"
  });


//Type should remain {a: string, b: string, c: string}
type ABC = typeof abc;

Link to playground

CodePudding user response:

No, there is currently (as of TypeScript 4.4) no type operator which checks that a value is assignable to a given (non-union) type without also widening it to that type. There is a longstanding open feature request for such an operator at microsoft/TypeScript#7481. If you want to see this happen you might go to that issue and give it a

  • Related