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

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.

主站蜘蛛池模板: 巴里| 根河市| 郧西县| 兴和县| 沅陵县| 简阳市| 合作市| 华池县| 大理市| 桐城市| 固镇县| 平潭县| 河源市| 福州市| 鸡泽县| 留坝县| 黄陵县| 双流县| 弋阳县| 慈溪市| 和田市| 色达县| 垦利县| 托里县| 泰兴市| 和静县| 凤台县| 周至县| 福建省| 阳朔县| 衡水市| 龙州县| 句容市| 句容市| 赫章县| 孝昌县| 宝应县| 潜江市| 蓬溪县| 龙川县| 甘肃省|