在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
In this lesson, we'll go over TypeScript's The main difference between the two types is that Another difference is that
function range(from: number, to: number): number[]; function range(from: unknown, to: unknown): number[] { if (typeof from !== "number" || typeof to !== "number") { throw Error("range() expects exactly 2 numbers"); } const values: number[] = []; for (let i = from; i < to; i++) { values.push(i); } return values; } console.log(range(0, 5)); Function overload: help user to see the correct type `number` instead od `unknown`. Why using `unknown` instead of `number` directly? function range(from: number, to: number): number[] { const values: number[] = []; for (let i = from; i < to; i++) { values.push(i); } return values; } It is good enough for the project you are working on with Typescript. But if it is a library. Users might use Javascript without typing system. Without `if type checking`, might casue issue. |
请发表评论