Home > Back-end >  typescript can not recognize indexed type properly
typescript can not recognize indexed type properly

Time:10-12

type X = {
  aa: string;
  bb: number;
};

const get = <Key extends keyof X, Value extends X[Key]>(
  key: Key,
  value: Value | ((v: Value) => Value)
) => {
  let newValue: Value;
  const x: X = {
    aa: '11',
    bb: 11
  };
  if (typeof value === 'function') {
    //Argument of type 'X[Key]' is not assignable to parameter of type 'Value'.
    newValue = value(x[key]);
  } else {
    newValue = value;
  }
};

Why "Argument of type 'X[Key]' is not assignable to parameter of type 'Value'."? In my opinion, X[Key] is exactly what Value is defined, how come it is not assignable? From a human being's view i.e. I calculate the type myself, there is no way to get the type wrong, why typescript can not tell?

CodePudding user response:

type X = {
  aa: string;
  bb: number;
};

const get = <Key extends keyof X>(
  key: Key,
  value: X[Key] | ((v: X[Key]) => X[Key])
) => {
  let newValue: X[Key];
  const x: X = {
    aa: '11',
    bb: 11
  };
  if (typeof value === 'function') {
    // Works now
    newValue = value(x[key]);
  } else {
    newValue = value;
  }
};

CodePudding user response:

get<'aa' | 'bb', string | number>('aa', 1) is a valid invocation

My initial intent is pass no generic param and let typescript bind it automatically, ignoring the fact that some evil generic param can be passed through

  • Related