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

The unknown type

unknown is a new type that has been added in TypeScript 3. Before TypeScript 3, we may have used the any type when we weren't sure of all the properties and methods in an object from a third-party library. However, when we declare a variable with the any type, the TypeScript compiler won't do any type checking on it. The unknown type can be used in these situations to make our code more type-safe. This is because unknown types are type-checked. So, unknown can often be used as an alternative to any.

In the TypeScript playground, let's go through an example of a function using any and an improved version using unknown:

  1. First, let's create a logScores function that takes in a parameter of type any. It logs out the name and scores properties from the argument to the console:
function logScores(scores: any) {
console.log(scores.firstName);
console.log(scores.scores);
}
  1. Let's call this function with the following:
logScores({
name: "Billy",
scores: [60, 70, 75]
});

If we run the program, we get undefined followed by [60, 70, 75] in the console. We passed in a correct object parameter, but our function logs firstName instead of name to the console. The program compiled just fine and didn't produce an error at runtime, but didn't give the result we wanted. This is all because we told the compiler not to check any types with the any type.

  1. Let's start to create a better version of this function with the unknown type:
function logScoresBetter(scores: unknown) {
console.log(scores.firstName);
console.log(scores.scores);
}

We immediately get compiler warnings where we reference the properties in scores:

So, the compiler is checking our scores variable now, which is great, and is even warning us about the firstName property. However, the scores property is also giving a complication error but is valid. So, how do we tell the compiler this? We need to explicitly do some type checking ourselves in our code. We'll cover a couple of ways of doing this in the following sections.

主站蜘蛛池模板: 平乡县| 扶沟县| 墨江| 寻乌县| 晋宁县| 会东县| 偃师市| 乌拉特后旗| 潮安县| 德惠市| 新巴尔虎右旗| 含山县| 江门市| 龙游县| 达拉特旗| 鄂伦春自治旗| 闽侯县| 高碑店市| 海南省| 三穗县| 罗甸县| 长寿区| 惠来县| 资源县| 遂昌县| 夏邑县| 易门县| 阳原县| 安图县| 昌黎县| 汉源县| 通海县| 阳朔县| 青阳县| 洪江市| 壤塘县| 潮州市| 沛县| 武功县| 天水市| 耒阳市|