我正在尝试使用 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?p>
最佳答案
当你有联合类型时,你会在原始使用它时看到任何共享成员。
如果你想使用更具体的成员,你需要使用类型保护。在类型保护内部,您将有权访问该类型的所有特定成员。
这是一个简化的例子:
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/