官术网_书友最值得收藏!

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:

  1. First, let's create a type alias for the structure we want the function parameter to be:
type Scores = { 
name: string;
scores: number[]
};
  1. 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.

主站蜘蛛池模板: 福泉市| 台北县| 乾安县| 永平县| 榕江县| 焦作市| 高邮市| 温州市| 鸡泽县| 奇台县| 河源市| 双流县| 宁安市| 平谷区| 盐边县| 正蓝旗| 中牟县| 读书| 肥东县| 攀枝花市| 太仆寺旗| 连平县| 高碑店市| 渑池县| 舒兰市| 红安县| 镇巴县| 额尔古纳市| 田东县| 玉屏| 永济市| 陕西省| 伊宁市| 天峻县| 施甸县| 十堰市| 武山县| 巴林左旗| 新巴尔虎左旗| 洞头县| 吕梁市|