- 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.
推薦閱讀
- JavaScript百煉成仙
- GAE編程指南
- 數(shù)據(jù)庫程序員面試筆試真題與解析
- Java 9 Concurrency Cookbook(Second Edition)
- Effective C#:改善C#代碼的50個(gè)有效方法(原書第3版)
- Power Up Your PowToon Studio Project
- Git高手之路
- 機(jī)械工程師Python編程:入門、實(shí)戰(zhàn)與進(jìn)階
- C語言程序設(shè)計(jì)案例精粹
- Android驅(qū)動(dòng)開發(fā)權(quán)威指南
- SQL Server 2012 數(shù)據(jù)庫應(yīng)用教程(第3版)
- 編程的原則:改善代碼質(zhì)量的101個(gè)方法
- Magento 2 Developer's Guide
- Tkinter GUI Application Development Blueprints
- 深度學(xué)習(xí)的數(shù)學(xué):使用Python語言