Learning TypeScript - Casting Types

前端 未结 1 1409
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 11:53

I\'m new to TypeScript and I\'m playing around with the various language features. Below is a code sample I\'ve been working on during one of the many online courses.

<
相关标签:
1条回答
  • 2020-12-10 12:31

    There is no type casting in Typescript, but only type assertions. This is for type checking and it won't influence runtime behavior.

    For example, the type assertion:

    car as Truck  // older syntax syntax: <Truck> car 
    

    tells the compiler that the car is of type Truck, but it won't influence the generated JS code.

    TypeScript allows you to override its inferred and analyzed view of types in any way you want to. This is done by a mechanism called "type assertion". TypeScript's type assertion is purely you telling the compiler that you know about the types better than it does, and that it should not second guess you.

    Type Assertion vs. Casting

    The reason why it's not called "type casting" is that casting generally implies some sort of runtime support. However type assertions are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed.

    https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html

    Update:

    Another good reference nowadays is the Typescript site itself

    Type assertions are a way to tell the compiler “trust me, I know what I’m doing.” A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler. TypeScript assumes that you, the programmer, have performed any special checks that you need.

    0 讨论(0)
提交回复
热议问题