string、 number、 boolean
js中的基本数据类型:string、number、boolean。在ts中对应的类型名称,和typeof操作符返回值一样。
- string, 比如
'Hello, world' - number,比如
42。js中没整型,没等价的int或者float类型,都是number类型 - boolean, 2个值,
truefalse
Arrays
[1,2,3]类型是number[]或者Array<number>['a', 'b']类型是string[]或者Array<string>
以此类推
any
ts中的特殊类型any。当一个值是any类型时,可以访问任何属性,像函数一样调用,赋值给任何一个类型。使用any类型可以跳过类型检查。
noImplicitAny
当不指定类型,或者ts不能从上下文推导出类型时,编译器就会默认这个值为any类型。设置noImplicitAny为true,抛出隐形any错误。
变量初始化时的类型
使用const, var, 或者let声明变量时,可以显示地指定变量的类型
let myName: string = "Alice";
一般不需要手动添加,ts会推导出类型。
函数
可以给函数入参、出参添加类型。
入参
// 参数类型
function greet(name: string) {
console.log("Hello, " + name.toUpperCase() + "!!");
}
当参数有类型时,调用时入参就会被类型检查。如果没参数,调用时会校验参数个数。
// Argument of type 'number' is not assignable to parameter of type 'string'.
greet(42);
返回值
function getFavoriteNumber(): number {
return 26;
}
函数返回值和变量类型一样,不需要指定类型。ts会自动推导。一些代码库为了防止意外或者个人习惯,会显示地添加返回类型。
匿名函数
const names = ["Alice", "Bob", "Eve"];
names.forEach(function (s) {
// s: string
console.log(s.toUpperCase());
});
尽管s没有类型说明,但是ts会根据forEach函数推导出s为string类型。
对象类型
function printCoord(pt: { x: number; y: number }) {}
可选属性
属性名后添加?成为可选属性
function printName(obj: { first: string; last?: string }) {}
联合类型
const n: number | string
类型收缩
利用类型判断进行类型收缩
function printId(id: number | string) {
if (typeof id === "string") {
// In this branch, id is of type 'string'
console.log(id.toUpperCase());
} else {
// Here, id is of type 'number'
console.log(id);
}
}
类型别名
type Point = {
x: number;
y: number;
};
function printCoord(pt: Point) {}
type ID = number | string;
接口
接口是定义对象的另外一种方式。
interface Point {
x: number;
y: number;
}
function printCoord(pt: Point) {}
类型别名和接口的区别
扩展
接口扩展(使用 extends)
interface Animal {
name: string
}
interface Bear extends Animal {
honey: boolean
}
类型别名扩展(使用&)
type Animal = {
name: string
}
type Bear = Animal & {
honey: boolean
}
新增字段
已存在的接口上添加字段
interface Window {
title: string
}
interface Window {
ts: TypeScriptAPI
}
类型别名创建后不能再更改
type Window = {
title: string
}
type Window = {
ts: TypeScriptAPI
}
// Error: Duplicate identifier 'Window'.
类型断言
使用断言指定一个更具体的类型
const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;
// <> 断言语法可以在.tsx文件外使用
const myCanvas = <HTMLCanvasElement>document.getElementById("main_canvas");
断言为一个不可能的类型会报错
const x = "hello" as number;
// Conversion of type 'string' to type 'number' may be a mistake...
有些场景,不生效时,可以使用2次断言。第一次断言为any或者unknown
const a = (expr as any) as T;
字面量类型
字面量类型
// x类型为 hello
let x: "hello" = "hello";
var let const 定义变量时,const声明的变量为字面量类型
// changingString 类型为 string
let changingString = "Hello World";
// constantString 类型为 "Hello World"
const constantString = "Hello World";
字面量类型可以与联合类型结合,可以校验具体值
function printText(s: string, alignment: "left" | "right" | "center") {}
boolean类型本质是type boolean = true | false
字面量接口
初始化一个变量为一个对象,对象的值是可以改变的
const obj = { counter: 0 };
if (someCondition) {
// obj.counter 类型为 number, 而不是字面量 0, 所以counter字段值可以更改
obj.counter = 1;
}
const req = { url: "https://example.com", method: "GET" };
// req.method 类型推断为 string
handleRequest(req.url, req.method);
// Argument of type 'string' is not assignable to parameter of type '"GET" | "POST"'.
2种方式解决
const req = { url: "https://example.com", method: "GET" as "GET" };
handleRequest(req.url, req.method as "GET");
// 整个对象转为类型字面量
const req = { url: "https://example.com", method: "GET" } as const;
handleRequest(req.url, req.method);
null和undefined
对应js中的2个基本类型。
strictNullChecks开启时,严格校验。
function doSomething(x: string | null) {
if (x === null) {
// do nothing
} else {
console.log("Hello, " + x.toUpperCase());
}
}
非空断言
function liveDangerously(x?: number | null) {
// No error
console.log(x!.toFixed());
}
枚举
enum Direction {
Up = 1,
Down,
Left,
Right,
}
其他基础数据类型
bigint
const oneHundred: bigint = BigInt(100);
const anotherHundred: bigint = 100n;
symbol
// const firstName: typeof firstName
const firstName = Symbol("name");