← 返回首页
Vue3基础教程(五)
发表时间:2021-08-02 16:36:35
类型注解

类型注解

所谓类型注解,就是为某个变量指定类型,例如:

const count: number = 123;
const word: string = '123';
//TypeScript中一个变量的类型并不一定是固定的,例如
let temp: string | number = '234';
temp = 123; // 这样也不会报错

我们来看看 TypeScript 工具带来的高级功能。 给 sayHello函数的参数添加 : string 类型注解,如下:

export {}
let name = 'zhangsan';
function sayHello(name: string) {
    console.log(`hello:${name}`);
}
sayHello(name);

TypeScript 里的类型注解是一种轻量级的为函数或变量添加约束的方式。 在这个例子里,我们希望 sayHello函数接收一个字符串参数。 然后尝试把 sayHello的调用改成传入一个数字:

export {}
let name = 100;
function sayHello(name: string) {
    console.log(`hello:${name}`);
}
sayHello(name);

重新编译,你会看到产生了一个错误:

- error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.

类似地,尝试删除 sayHello 调用的所有参数。 TypeScript 会告诉你使用了非期望个数的参数调用了这个函数。 在这两种情况中,TypeScript提供了静态的代码分析,它可以分析代码结构和提供的类型注解。

注意:尽管hello.ts编译错误,但是hello.js 文件还是被创建了。 就算你的代码里有错误,你仍然可以使用 TypeScript。但在这种情况下,TypeScript 会警告你代码可能不会按预期执行。