TypeScript 或 JavaScript 类型转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13204759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:55:20  来源:igfitidea点击:

TypeScript or JavaScript type casting

castingtypescript

提问by Klaus Nji

How does one handle type casting in TypeScript or Javascript?

如何处理 TypeScript 或 Javascript 中的类型转换?

Say I have the following TypeScript code:

假设我有以下 TypeScript 代码:

module Symbology { 

    export class SymbolFactory { 

        createStyle( symbolInfo : SymbolInfo) : any { 
            if (symbolInfo == null)
            {
                 return null;
            }

            if (symbolInfo.symbolShapeType === "marker") {      

                // how to cast to MarkerSymbolInfo          
                return this.createMarkerStyle((MarkerSymbolInfo) symbolInfo);
            }                                  
        }

        createMarkerStyle(markerSymbol : MarkerSymbolInfo ): any { 
            throw "createMarkerStyle not implemented";
        }              

    }
}

where SymbolInfois a base class. How do I handle typecasting from SymbolInfoto MarkerSymbolInfoin TypeScript or Javascript?

哪里SymbolInfo是基类。如何在 TypeScript 或 Javascript 中处理从SymbolInfoto 的类型转换MarkerSymbolInfo

回答by blorkfish

You can cast like this:

你可以这样投射:

return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);

Or like this if you want to be compatible with tsx mode:

或者像这样,如果你想与 tsx 模式兼容:

return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);

Just remember that this is a compile-time cast, and not a runtime cast.

请记住,这是一个编译时强制转换,而不是运行时强制转换。

回答by Alex

This is called type assertionin TypeScript, and since TypeScript 1.6, there are two ways to express this:

这在 TypeScript 中称为类型断言,从 TypeScript 1.6 开始,有两种表达方式:

// Original syntax
var markerSymbolInfo = <MarkerSymbolInfo> symbolInfo;

// Newer additional syntax
var markerSymbolInfo = symbolInfo as MarkerSymbolInfo;

Both alternatives are functionally identical. The reason for introducing the as-syntax is that the original syntax conflicted with JSX, see the design discussion here.

这两种选择在功能上是相同的。引入as-syntax的原因是原始语法与JSX冲突,请参阅此处的设计讨论。

If you are in a position to choose, just use the syntax that you feel more comfortable with. I personally prefer the as-syntax as it feels more fluent to read and write.

如果您可以选择,请使用您觉得更舒服的语法。我个人更喜欢as-syntax,因为它读起来更流畅。