Home > Enterprise >  Literal values in object type inference
Literal values in object type inference

Time:03-08

This is quite verbose:

interface Point {
  x: 1;
  y: 2;
}

const point: Point = {
  x: 1,
  y: 2,
};

// The inferred type would have been
// { x: number; y: number; }

Is there any way to use type inference here but to force values to be literals?

CodePudding user response:

Use as const:

const point = {
  x: '1',
  y: '2',
} as const; // { x: '1'; y: '2'; }
  • Related