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

How to get a definite type when accessing an object?

interface MyProps {
  x: number;
  y: string;
}

const myVar: MyProps = {
  x: 1,
  y: '2',
};

function getMyValue(prop?: keyof MyProps) {
  if (prop) {
    return myVar[prop];
  }
  return myVar;
}

const x = getMyValue('x');
const y = getMyValue('y');
const val = getMyValue();

Now I get the type of x is string | number | MyProps, but what I expect x is number, y is string, and val is MyProps. So, how to do that?

>Solution :

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

You have to use generics and function overloads:

interface MyProps {
  x: number;
  y: string;
}

const myVar: MyProps = {
  x: 1,
  y: '2',
};

function getMyValue<Prop extends keyof MyProps = keyof MyProps>(prop: Prop): MyProps[Prop]

function getMyValue(): MyProps

function getMyValue<Prop extends keyof MyProps = keyof MyProps>(prop?: Prop): MyProps[Prop] | MyProps {
  if (prop) {
    return myVar[prop];
  }
  return myVar;
}

Typescript playground

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