(六)TypeScript入门 | 青训营笔记

20 阅读1分钟

“这是我参与「第五届青训营」伴学笔记创作活动的第 6 天”

主要内容

1 为什么是TypeScript?

1.1 JS vs TS

  • JS
    • 动态类型
    • 弱类型语言
  • TS
    • 静态类型
      • 可读性增强:基于语法解析TSDoc,ide增强
      • 可维护性增强:在编译阶段暴露大部分错误
      • 多人合作的大型项目中,获得更好的稳定性和开发效率
    • 弱类型语言
    • JS的超集
      • 包含于兼容所有JS特性,支持共存
      • 支持渐进式引入与升级

2 基本语法

2.1 基础数据类型

/* 字符串 */
const q: string = 'string';
/* 数字 */
const w: number = 1;
/* 布尔值 */
const e: boolean = true;
/* null */
const r: null = null;
/* undefined */
const t: undefined = undefined;

2.2 对象类型

这里对于interface的命名前会加一个大写字母I,例如IBytedancer,是对接口类型约定俗成的命名方法。

const bytedancer: IBytedancer = {
  jobId: 9303245,
  name: 'Lin',
  sex: 'man',
  age: 28,
  hobby: 'swimming',
}

interface IBytedancer {
  /* 只读属性:约束属性不可再对象初始化外赋值 */
  readonly jobId: number;
  name: string;
  sex: 'man' | 'woman' | 'other';
  age: number;
  /* 可选属性:定义该属性可以不存在 */
  hobby?: string;
  /* 任意属性:约束所有对象属性都必须是该属性的子类型 */
  [key: string]: any;
}

/* 报错:无法分配到"jobId",因为它是只读属性 */
// bytedancer.jobId = 12345;
/* 成功:任意属性标注下可以添加任意属性 */
bytedancer.platform = 'data';
/* 报错:缺少属性"name",hobby可缺省 */
// const bytedancer2: IBytedancer = {
//   jobId: 89757,
//   sex: 'woman',
//   age: 18,
// }

2.3 函数类型

interface IMult {
  (x: number, y: number): number;
}
const mult: IMult = (x, y) => x * y;
function add(x: number, y: number): number {
  return x + y;
}
const mult: (x: number, y: number) => number = (x, y) => x * y;