简体   繁体   English

在TypeScript中键入Assertion而不指定新变量

[英]Type Assertion in TypeScript without assigning a new variable

I have a function that returns values with one of two interfaces, like so: 我有一个函数,它使用两个接口之一返回值,如下所示:

interface K {
    A:number;
    NUM:number;
}

interface L {
    A:string;
    STR:string;
}

function FUN():K|L { }

var x:K|L = FUN();

but I can't access the non-shared property using a type-guard like this one: 但我不能使用像这样的类型保护访问非共享属性:

if(typeof x.A === 'string'){
    console.log(x.STR) // Property 'STR' does not exist on type 'K | L'
}

even though the if clause does distinguish between the two types. 即使if子句确实区分了这两种类型。 I know I can use as operator with a variable assignment to indicate the type to the compiler like so: 我知道我可以使用as运算符与变量赋值指示类型编译器,像这样:

if(typeof x.A === 'string'){
    var y = x as L;
    console.log(y.STR) // OK 
}

but that seems a bit kludgy as this add a unnecessary var statement and assignment in the resulting js code: 但这看起来有点kludgy,因为这会在生成的js代码中添加一个不必要的var语句和赋值:

function FUN() { }
var x = FUN();
if (typeof x.A === 'string') {
    var y = x; // unnecessary...
    console.log(y.STR); 
}

Is there any way to indicate the type in this situation without the extra var y=x; 如果没有额外的var y=x;有没有办法在这种情况下指明类型var y=x; in the JS code? 在JS代码中?

Yes, TypeScript supports type casting. 是的,TypeScript支持类型转换。 You should be able to do: 你应该能够做到:

if(typeof x.A === 'string'){
    console.log((<L>x).STR);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM