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

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.

主站蜘蛛池模板: 白玉县| 天峨县| 会泽县| 阿荣旗| 阳曲县| 科技| 岑巩县| 内黄县| 徐水县| 河间市| 五华县| 牡丹江市| 全南县| 晋宁县| 敖汉旗| 北流市| 宁晋县| 黎川县| 昆明市| 大石桥市| 城口县| 井陉县| 诏安县| 定日县| 文水县| 河西区| 滨州市| 理塘县| 林甸县| 宁化县| 瑞昌市| 延津县| 土默特左旗| 长宁县| 延川县| 黔西县| 昂仁县| 罗平县| 邹平县| 本溪市| 平陆县|