typescript - 如何在 Typescript 中使用联合类型的返回值?

标签 typescript

我正在尝试使用 shelljs (通过 DefinitelyTyped )在 Typescript 1.5-beta 中。在我的代码中,我想使用 exec具有以下签名的函数:

export function exec(command: string, options: ExecOptions): ExecOutputReturnValue | child.ChildProcess;

export interface ExecOutputReturnValue
{
    code: number;
    output: string;
}

如果我按如下方式导入和使用库(在正常的 ES6 JavaScript 中工作得很好)

import * as $ from 'shelljs';
const code =  $.exec(command, { silent: true }).code;

Typescript 编译器给我 error TS2339: Property 'code' does not exist on type 'ChildProcess | ExecOutputReturnValue' .

如何以类型安全的方式访问 .code?

最佳答案

当你有联合类型时,你会在原始使用它时看到任何共享成员。

如果你想使用更具体的成员,你需要使用类型保护。在类型保护内部,您将有权访问该类型的所有特定成员。

这是一个简化的例子:

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.
}

当您处理无法应用 typeof 检查的类型时,您需要告诉编译器“您最了解”:

const code =  (<ExecOutputReturnValue >$.exec(command, { silent: true })).code;

关于typescript - 如何在 Typescript 中使用联合类型的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31437604/

相关文章:

testing - 在生产模式下隐藏 angular2 组件的最佳解决方案?

typescript - fp-ts在mapLeft内部调用异步函数

javascript - 如何通过 RxJS 限制对 React 组件方法的调用

javascript - 在 map 中的特定索引处插入

javascript - Angular 2组件指令不起作用

javascript - 如何在 firebase 中实时删除特定子项(Angular 7)

javascript - 如何在 redux-toolkit 中输入 'prepare' 函数

javascript - *ng如果 Angular 没有绑​​定正确的值

javascript - 为什么我不能将 typescript 泛型类型分配给该类型的联合?

html - 在 Angular 2 中使用路由器 socket