我可以在块范围内对变量进行类型转换吗?

Kag*_*ght 7 typescript

我有这个代码:

function foo(input: Blob): void;
function foo(input: string): void;
function foo(input: any) {
    if (typeof input === "string") {

    }   
    else if (input instanceof Blob) {

    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,我想input在块范围内进行类型转换,而不是将其重新分配给另一个变量。

if (typeof input === "string") {
    declare input: string;
}   
else if (input instanceof Blob) {
    declare input: Blob;
}
Run Code Online (Sandbox Code Playgroud)

而不是:

if (typeof input === "string") {
    var str: string = input;
}   
else if (input instanceof Blob) {
    var blob: Blob = input;
}
Run Code Online (Sandbox Code Playgroud)

这在 TypeScript 中可能吗?

Wal*_*ter 6

我认为最新版本的 TypeScript 会自动执行此操作。但是您必须将 if 语句与typeof,instanceof或特殊函数一起使用。

function foo(input: string|blob|whatever) {
    if(typeof input === 'string') {
        // input is now a string
        input.blobfunction(); // Error: blobfunction() is not a method of string
    } else if(input instanceof blob) {
        // input is now a blob
    } else if(isWhatever(input)) {
        // input is now a whatever
    }
}

// Probably a good idea to make this a static 'whatever.isInstance()'
function isWhatever(input: string|blob|whatever): input is whatever {
    return true; // put your test for whatever here
}
Run Code Online (Sandbox Code Playgroud)

请参阅:https://www.typescriptlang.org/docs/handbook/advanced-types.html


归档时间:

查看次数:

1212 次

最近记录:

4 年,5 月 前