我正在尝试在TypeScript1.5测试版中使用shelljs (通过DefinitelyTyped)。在我的代码中,我想使用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?
发布于 2015-07-16 04:18:24
当您有一个联合类型时,当您使用它时,您将看到任何共享成员。
如果要使用更具体的成员,则需要使用类型保护。在类型保护内部,您将可以访问该类型的所有特定成员。
下面是一个精简的示例:
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;发布于 2020-01-25 14:30:40
这是一个古老的问题,但如果有人遇到它,这可能会有所帮助。在较新版本的TS中,将用户定义的类型保护与类型谓词一起使用的比简单地“告诉编译器您最了解的”更安全,并且可以帮助避免在您认为最了解但实际上不知道的情况下出现运行时错误:-)。
使用OPs示例:
import * as $ from 'shelljs';
// our user-defined type guard, note the return type
const isExecOutput = (result: ExecOutputReturnValue | child.ChildProcess): code is ExecOutputReturnValue => {
return (result as ExecOutputReturnValue).code !== undefined;
}
const result: ExecOutputReturnValue | child.ChildProcess = $.exec(command, { silent: true });
if (isExecOutput(result)) {
doSomething(result.code); // safe!
} else {
// ... accessing the other type's members is safe here
}实现这一点的关键是isExecOutput函数的返回类型:code is ExecOutputReturnValue。称为类型谓词,它使用户定义的类型保护成为可能。官方文档可以在here上找到。
https://stackoverflow.com/questions/31437604
复制相似问题