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

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.

主站蜘蛛池模板: 庆城县| 商南县| 和平县| 加查县| 桃源县| 兰西县| 醴陵市| 临泉县| 玉环县| 乌拉特前旗| 南岸区| 衡阳县| 岳阳县| 青田县| 岑巩县| 柘城县| 奇台县| 招远市| 迭部县| 余江县| 精河县| 岳西县| 晋城| 镇安县| 炎陵县| 普兰县| 苗栗县| 永年县| 富阳市| 慈溪市| 石城县| 娄底市| 南木林县| 蚌埠市| 桦甸市| 淮阳县| 海阳市| 乳源| 保定市| 响水县| 洪湖市|