乐闻世界logo
搜索文章和话题

What are the two syntaxes for type assertions in TypeScript?

1个答案

1

In TypeScript, type assertion is a way to tell the compiler 'I know what I'm doing'. It allows you to treat a variable as a type you are confident about. TypeScript offers two syntaxes for type assertions:

1. Angle-bracket syntax

In this syntax, you place the target type within angle brackets and position it before the value you're asserting. For example, if you have a variable value of type any but you are confident it is a string, you can use angle-bracket syntax as follows:

typescript
let someValue: any = "this is a string"; let strLength: number = (<string>someValue).length;

Here, <string> tells the compiler 'trust me, someValue is a string'. Then you can safely access the length property of the string.

2. as syntax

Because angle-bracket syntax conflicts with HTML tags in JSX, TypeScript also provides as syntax. This approach can be used for type assertions and appears more natural. Using the same example, you can write it as:

typescript
let someValue: any = "this is a string"; let strLength: number = (someValue as string).length;

In this code, someValue as string tells the compiler that someValue should be treated as a string type.

Instance Application

Suppose you are working with a complex object from a third-party API, and you know the specific type of a certain property, but TypeScript infers the type as any by default. In this case, type assertions help you specify and use the property's type more accurately. For example:

typescript
// Assume data is the result from an API let data: any = { id: 10, name: "John Doe" }; // Asserting id is a number let id: number = (data as { id: number }).id;

Here, by (data as { id: number }), we tell TypeScript that the data object has an id property of type number, allowing you to avoid type-related errors and fully leverage TypeScript's type-checking capabilities.

2024年7月29日 13:26 回复

你的答案