- 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.
推薦閱讀
- 解構產品經理:互聯網產品策劃入門寶典
- CockroachDB權威指南
- Cocos2d-x游戲開發:手把手教你Lua語言的編程方法
- Learning Linux Binary Analysis
- Koa開發:入門、進階與實戰
- Java Web基礎與實例教程
- PHP+MySQL網站開發項目式教程
- AIRIOT物聯網平臺開發框架應用與實戰
- HTML5從入門到精通(第4版)
- Learning jQuery(Fourth Edition)
- Test-Driven Development with Django
- iPhone應用開發從入門到精通
- Python程序設計與算法基礎教程(第2版)(微課版)
- Python:Deeper Insights into Machine Learning
- Python語言科研繪圖與學術圖表繪制從入門到精通