Home > Enterprise >  How to get a definite type when accessing an object?
How to get a definite type when accessing an object?

Time:01-10

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?

CodePudding user response:

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

  •  Tags:  
  • Related