Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Literal values in object type inference

This is quite verbose:

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

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

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Numbers are not strings :

const point = {
    x: '1',
    y: '2',
}  // {    x: string; y: string; }

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

And if you want them as literals, use as const

const point = {
    x: '1',
    y: '2',
} as const; // {    x: '1'; y: '2'; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading