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

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.

主站蜘蛛池模板: 怀安县| 陆良县| 芦山县| 丰原市| 绿春县| 枣阳市| 武冈市| 横峰县| 桦甸市| 启东市| 温宿县| 罗定市| 罗源县| 邢台市| 云龙县| 东台市| 青铜峡市| 韶山市| 宁夏| 定兴县| 米林县| 汪清县| 宿州市| 奉新县| 哈巴河县| 正蓝旗| 集贤县| 海门市| 安图县| 四子王旗| 湖口县| 乌拉特后旗| 惠来县| 龙川县| 沅陵县| 新昌县| 玉田县| 偏关县| 柯坪县| 澜沧| 东丽区|