- 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.
推薦閱讀
- Vue.js設計與實現
- Java面向對象思想與程序設計
- 數據結構與算法JavaScript描述
- PostgreSQL Replication(Second Edition)
- MySQL數據庫基礎實例教程(微課版)
- 零基礎學Python網絡爬蟲案例實戰全流程詳解(入門與提高篇)
- JavaScript程序設計:基礎·PHP·XML
- C語言程序設計實訓教程與水平考試指導
- Python網絡爬蟲實例教程(視頻講解版)
- 百萬在線:大型游戲服務端開發
- Kotlin語言實例精解
- Manage Your SAP Projects with SAP Activate
- C語言編程魔法書:基于C11標準
- Scala編程(第4版)
- C++ Data Structures and Algorithm Design Principles