How to use return value of union type in Typescript?
I'm trying to use shelljs (via DefinitelyTyped ) in Typescript 1.5 beta. In my code, I would like to use a function exec
that has the following signature:
export function exec(command: string, options: ExecOptions): ExecOutputReturnValue | child.ChildProcess;
export interface ExecOutputReturnValue
{
code: number;
output: string;
}
If I import and use the library like this (which works fine in normal ES6 JavaScript)
import * as $ from 'shelljs';
const code = $.exec(command, { silent: true }).code;
the Typescript compiler gives me error TS2339: Property 'code' does not exist on type 'ChildProcess | ExecOutputReturnValue'
.
What can I do to access the .code in a safe way?
source to share
When you have a union type, you will see general users when you use it raw.
If you want to use more specific elements, you need to use the type defender. Inside a type guard, you will have access to all specific members of the type.
Below is an example:
declare class Test {
example(): string | number;
}
var x = new Test();
var y = x.example();
if (typeof y === 'string') {
// In here, y has all the members of a string type
y.
} else {
// In here, y has all the members of a number type
y.
}
When you are dealing with types that you cannot check typeof
, you need to tell the compiler that "you know better":
const code = (<ExecOutputReturnValue >$.exec(command, { silent: true })).code;
source to share