How can I infer from the parameter type in ts?

for example:

interface A {
  a: number
}

interface B {
  a: number
  b: string
}

const X = (x) => {
  // 
  return x
}
The

parameter x may be An or B.

if type An is passed in, you want to check that x is returned after the operation, and if you have the attribute b, it is an error.
if type B is passed in, you want to check that x is returned after the operation, and it is an error without attribute b.

you want to return the type of x, and the assertion is equal to the type passed in.

Apr.11,2021

A handwritten overload can be done


ts ts

:

interface A {
  a: any
}

interface B {
  a: any
  b: any
}

function isB(arg: A | B): arg is B {
    return (<B>arg).b !== undefined;
}

function foo(arg: A | B) {
  if (isB(arg)) {
    // arg is B
    console.log(arg.a, arg.b)
  } else {
    // arg is A
    console.log(arg.a)
  }
}

if I understand it wrong, ignore it, the big god spurts

Menu