TypeScript 初体验

分类:JavaScript     发布时间:2017-05-04     最后更新:2021-09-08     浏览数:1492
学习 TypeScript

解构

// 数组解构
let [first, second] = [10, 20];
console.log(first, second); // 10, 20

// 对象解构
const {a, ...rest} = {a: 10, b: 10, c: 99};
console.log(a, rest); // 10, {b: 10, c: 99};

枚举

export enum DIRECTIONS = {
  UP = 1,
  RIGHT = 2,
  DOWN = 3,
  LEFT = 4
}

类型别名和接口

// 类型别名
type Animal = {
  type: string;
};

type Dog = Animal & {
  bark: Function;
};

const dog: Dog = {
  type: "dog",
  bark: () => {},
};

// 接口
interface Animal {
    type: string;
}

interface Dog extends Animal {
    bark: Function;
}

const a: Dog = {
    type: 'dog',
    bark: () => {

    }
}

泛型

const a: Array<string> = ['a', 'b'];

function get<T>(url: string): Promise<T> {
  return fetch(url, {
    method: "get",
    headers: new Headers({
      Accept: "application/json",
    }),
  }).then((response) => response.json());
}
上一篇: PHP 日期及时间处理包 Carbon 下一篇: CSS3 左右固定大小,中间自适应