在TypeScript中,您可以使用联盟类型来描述可能具有多个类型的值,因此可以避免使用任何类型。
例如,假设函数定义使用描述值的参数,这些值可以是字符串或数字。
1function add(v1: any, v2: any) {
2 let value1 = typeof v1 === "string" ? +v1 : v1;
3 let value2 = typeof v2 === "string" ? +v2 : v2;
4
5 console.log(value1 + value2);
6}
7
8add(23, "32"); // 55
9add(23, true); // No error when passing non-string or number value
你可以这样做:
1function add(v1: number | string, v2: number | string) {
2 let value1 = typeof v1 === "string" ? +v1 : v1;
3 let value2 = typeof v2 === "string" ? +v2 : v2;
4
5 console.log(value1 + value2);
6}
7
8add(23, "32"); // 55
9add(23, true); // Error when passing non-string or number value