Home > Back-end >  Can a typescript function output 2 different data types?
Can a typescript function output 2 different data types?

Time:09-15

I have a function that could either output a string or undefined value. I've currently separated either output with the | operator. Is this correct, or is there a better way?

export function retrievePath(specFile: any): string | undefined{
  // ...
};

CodePudding user response:

That's correct.

In another way, you can define a type of string | undefined.

type PathType = string | undefined;

export function retrievePath(specFile: any): PathType {
  // ...
}
  • Related