基础使用
在 TS 中我们可以直接使用 ES 的新特性,并且完全兼容 JS 代码。
yarn add typescript --dev
bin 目录下的 tsc (typescript compile)就可以帮我们编译 ts 代码
const a:string // 类型注解
基础数据类型
-
number
-
string
-
boolean
-
void
-
null
-
undefined
-
void:一般表示函数没有返回值
-
元组:就是明确了元素类型和长度的数组
-
enum:表示一些状态的变量集合
const enum Gender { MALE = 'male', // 默认是0 FAMALE = 'female' }
-
联合类型:只能是A或者只能是B
-
交叉类型:既可以是A也可以是B
interface Foo { foo: string; name: string; } interface Bar { bar: string; name: string; } const sayHello = (obj: Foo & Bar) => { }; sayHello({ foo: "foo", bar: "bar", name: "kakuqo" });
-
object 使用细节
// object不单指对象,可以是如下值 {} [] function() {} const foo: object = [] // 如果想要单指对象,可以如下操作 const obj: {} = { foo: 'foo' }
配置文件
yarn tsc --init 生成配置文件
target: "es5" // 编译后采用的标准
module: "commonjs" // 模块化标准
...
执行 yarn tsc 配置文件即生效
标准库
指的是内置对象所对应的声明
const d:symbol = Symbol()
这么写只有把配置文件的target设置为 es2015 才不会报错
报错的话可能是设置为了es5,会找不到Symbol或者Promise的声明
如果继续用es5的话,也可以在lib里面引用标准库
{
"compilerOptions": {
"target": "es5",
"lib": ["ES2015", "DOM"] // 像dom和bom都归在了DOM中
}
}
类型声明
第三方npm模块不一定用TS,一般需要安装对应的类型声明模块。才能获得对应的代码补全,接口提示等等功能
如果第三方模块不包含对应的类型声明文件,就可以尝试安装对应的类型声明模块,一般就是@types/模块名,这样就有对应的类型提示了,.d.ts 后缀的文件,是 ts 中专门用来做类型声明的文件,也就是类型声明模块
有些模块可能自己就包含了,不需要主动下载
yarn add @types/ladash --dev
如果没有的话就只能自己用declare语句来声明对应的模块类型。
import { camelCase } from 'lodash' // Error
declare function camelCase(input: string): string
const res = camelCase('h')
类型别名
比如一个函数类型我们每次写那么一长串就很累
function sum(x: number, y: number): number {
return x + y
}
就可以起别名
type PlusType = (x: number, y: number) => number
const sum2: PlusType = sum
类型断言
明确告诉ts我这就是某个类型
let a = res as number
let a = <number>res // 也可以用尖括号进行断言,但是会跟jsx产生冲突
隐式类型推断
其实就是如果不写类型会自动帮你判断,以后也不能用其他的类型
接口
其实就是约定对象的结构
interface Post { // 分号也可不加
title: string;
subtitle?: string;
readonly summary: string;// 初始化之后就不能再修改了
[key: string]: string; // 动态成员
}
const post: Post = ...