- Learn React with TypeScript 3
- Carl Rippon
- 320字
- 2021-06-10 19:16:43
Type checking with a type predicate
One way we can perform type checking in a function is with another function that has a return type as a type predicate. Let's explore this and eventually create a new version of our logScores function:
- First, we'll define a new function called scoresCheck to do the necessary type checking:
const scoresCheck = (
scores: any
): scores is { name: string; scores: number[] } => {
return "name" in scores && "scores" in scores;
};
This takes in a scores parameter that has a type predicate, scores is { name: string; scores: number[] }, ensuring it contains the correctly typed name and scores properties. The function simply returns whether the scores parameter contains the name and scores properties.
- Let's use this function in our logScores function:
function logScores(scores: unknown) {
if (scoresCheck(scores)) {
console.log(scores.firstName);
console.log(scores.scores);
}
}
We immediately get the compilation error we want:
The type predicate, scores is { name: string, scores: number[] }, allows the TypeScript compiler to narrow down the type in the if block that logs the properties to the console. This results in scores.scores compiling fine, but scores.firstName is giving an error, which is just what we want.
The type predicate is the key bit. Without it, the TypeScript compiler will still throw errors on the valid scores.scores reference. Try removing the type predicate and see for yourself.
Note that we can make the predicate a little more readable with a type alias:
type Scores = { name: string; scores: number[] }
const scoresCheck = (
scores: any
): scores is Scores => {
return "name" in scores && "scores" in scores;
};
Using a type predicate in this way is called a type guard. There are other ways of implementing type guards, which we'll cover later in the book.
- 零基礎學C++程序設計
- Python從小白到大牛
- Learning Selenium Testing Tools with Python
- .NET 4.0面向對象編程漫談:基礎篇
- Java程序員面試算法寶典
- UI智能化與前端智能化:工程技術、實現(xiàn)方法與編程思想
- 薛定宇教授大講堂(卷Ⅳ):MATLAB最優(yōu)化計算
- 征服RIA
- Expert Android Programming
- Oracle Exadata專家手冊
- Webpack實戰(zhàn):入門、進階與調優(yōu)
- Learning Material Design
- C++ Application Development with Code:Blocks
- Python Programming for Arduino
- iOS Development with Xamarin Cookbook