- Learn React with TypeScript 3
- Carl Rippon
- 190字
- 2021-06-10 19:16:43
Type narrowing with a type assertion
The other way of performing type checking we are going to look at when using unknown is to use type assertion. Type assertion lets us tell the compiler what the type is with the as keyword.
Let's create yet another version of our logScores function as an example:
- First, let's create a type alias for the structure we want the function parameter to be:
type Scores = {
name: string;
scores: number[]
};
- In our logScores function, we can now use the as keyword to tell the compiler what type to expect:
function logScores(scores: unknown) {
console.log((scores as Scores).firstName);
console.log((scores as Scores).scores);
}
That's enough information for the compiler to pinpoint the problem:
The unknown type allows us to reduce our use of the any type and create more strongly-typed and robust TypeScript programs. We do have to write more code, though, when referencing unknown types. The additional code we need to write needs to check the type of the unknown variable so that the TypeScript compiler can be sure we are accessing valid members within it.
推薦閱讀
- 軟件界面交互設計基礎
- 數據結構和算法基礎(Java語言實現)
- Building Mobile Applications Using Kendo UI Mobile and ASP.NET Web API
- 小程序,巧運營:微信小程序運營招式大全
- SAP BusinessObjects Dashboards 4.1 Cookbook
- Spring Boot進階:原理、實戰與面試題分析
- Python時間序列預測
- Learning Vaadin 7(Second Edition)
- Unity 2017 Mobile Game Development
- 移動互聯網軟件開發實驗指導
- 響應式Web設計:HTML5和CSS3實戰(第2版)
- BeagleBone Robotic Projects(Second Edition)
- Python青少年趣味編程
- Python一行流:像專家一樣寫代碼
- Python 3.6從入門到精通(視頻教學版)