类型注解(手动)

告诉typescript值得类型是什么

  1. // 只能是number类型的值
  2. const score:number = 50;
  1. let balls: string[] = ['basketball', 'football', 'volleyball'];
  1. class Car {}
  2. let car: Car = new Car();
  1. let person: {
  2. name: string;
  3. age: number;
  4. } = {
  5. name: "张三",
  6. age: 20
  7. }
  1. // 参数、返回值
  2. const logNumber: (num: number) => void = (num: number) => {
  3. }

类型推断(自动)

当变量声明和变量初始化在同一行的时候,类型推断系统才会起作用。
image.png

什么时候使用注解?

  1. 当一个函数返回any类型但是我们想要一个具体的类型
  2. 当某一行声明变量声明后,在另一行进行初始化
  3. 当我们想要一个变量拥有一个不能推断出来的类型

    1. let num: boolean | number = false;
  4. 我们应该尽可能多的使用类型推断,少使用类型注解

    JSON.parse()

    返回值的类型是any类型,我们一般也需要添加注解
    2.类型注解、类型推断初探 - 图2

    函数的类型注解

  5. 参数必须要加类型注解,返回值会根据参数进行推断 ```typescript const addNums = (a: number, b: number): number => { return a + b; }

function multiply(a: number, b: number): number { return a + b; } // 无返回值的类型注解 const logger = (mas: string): void { console.log(mas); }

  1. 2. 函数参数的类型注解
  2. ```typescript
  3. const todayWeather = {
  4. date: new Date(),
  5. weather: '晴天'
  6. }
  7. const logWeather = (todayWeather: {
  8. date: Date,
  9. weather: string
  10. }): void => {
  11. console.log(todayWeather.date);
  12. console.log(todayWeather.weather);
  13. }
  14. logWeather(todayWeather);
  1. const todayWeather = {
  2. date: new Date(),
  3. weather: '晴天'
  4. }
  5. const ES6 = ({
  6. date,
  7. weather
  8. }: {
  9. date: Date,
  10. weather: string
  11. }) => {
  12. console.log(date);
  13. console.log(weather);
  14. }
  15. ES6(todayWeather);

对象的类型注解

  1. const profile = {
  2. nameL: "Mike",
  3. age: 20,
  4. coords: {
  5. lat: 30,
  6. lng: 50
  7. },
  8. setAge(age: number): void {
  9. this.age = age;
  10. }
  11. }
  12. const {
  13. age
  14. }: {
  15. age: number
  16. } = profile;
  17. const {
  18. coords: {
  19. lat,
  20. lng
  21. }
  22. }: {
  23. coords: {
  24. lat: number;lng: number
  25. }
  26. } = profile;