基本数据类型
undefined
和 null
可赋值给其他基本数据类型
let num: number = 3;
let flag: boolean = false;
let str: string = "abc";
let a: null = null;
let b: undefined = undefined;
联合数据类型
let variable: number | boolean = false;
variable = 123;
数组
伪数组不能赋值给数组,数据类型是any[]
也不行
let arrOfNumbers: number[] = [1, 2, 3, 4];
arrOfNumbers.push(5);
// 若push其他数据类型会报错
function test() {
console.log(arguments);
}
元组Tuple
// 多一项少一项都会报错
let user: [string, number] = ['viking', 20];
Interface 接口
- 对对象的形状(shape)进行描述
- 对类(class)进行抽象
- Duck Typing(鸭子类型)
?
可选属性
readonly
只读属性,创建时赋值
const 用在变量上边
readonly用在属性上边
// 用分号进行分割
interface Person {
readonly id: number;
name: string;
age?: number;
}
let viking: Person = {
id: 1111,
name: 'viking',
age: 20
}
函数和类型推断
可选参数只能放在后边
函数声明
function add(x: number, y: number, z?: number): number {
if (typeof z === 'number') {
return x + y + z;
}
else {
return x + y;
}
}
函数表达式
const add = function(x: number, y: number, z?: number): number {
if (typeof z === 'number') {
return x + y + z;
}
else {
return x + y;
}
}
const add2: (x: number, y: number, z: number) => number = add
类class
private
, public
, protected
, readonly
, static
class Animal {
// name不能被修改
readonly name: string,
// 没有实例也可以调用的静态属性
static isAnimal (a) {
return a instanceof Animal;
}
constructor(name: string) {
this.name = name;
}
run() {
return `${this.name} is running`;
}
}
const snake = new Animal('snake');
console.log(snake.run());
class Dog extends Animal {
bark() {
return `${this.name} is barking`;
}
}
const dog = new Dog('dog');
class Cat extends Animal{
constructor(name){
super(name);
console.log(this.name);
}
// 方法重写
run() {
return 'Meow, ' + super.run();
}
}
特性抽取
interface Radio {
switchRadio(): void;
}
interface Battery {
checkBatteryStatus(): void;
}
interface RadioWithBattery extends Radio {
checkBatteryStatus(): void;
}
class Car implements Radio {
switchRadio() {
}
}
// class Cellphone implements RadioWithBattery
class Cellphone implements Radio, Battery {
switchRadio{
}
checkBatteryStatus() {
}
}
枚举
enum Direction {
Up,
Down,
Left,
Right
};
console.log(Direction.Up);
console.log(Direction[0]);
js赋值运算符返回的是被赋予的值
console.log(Direction['Up'] = 0); // 0
编译后的js文件
enum Direction {
Up = 'UP',
Down = 'DOWN',
Left = 'LEFT',
Right = 'RIGHT'
};
const value = 'UP';
if (value === Direction.Up) {
console.log('go up')
}
常量枚举
const enum Direction {
Up = 'UP',
Down = 'DOWN',
Left = 'LEFT',
Right = 'RIGHT'
};
const value = 'UP';
if (value === Direction.Up) {
console.log('go up')
}
编译后的js文件,直接显示Direction.Up对应的变量,而不显示枚举建立的过程
泛型
基础用法
function echo<T>(arg: T): T {
return arg;
}
function swap<T, U> (tuple: [T, U]): [U: T] {
return [tuple[1], tuple[0]];
}
const res = swap(['str', 123]);
约束泛型
function echoWithArr<T>(arg: T[]): T[] {
console.log(arg.length);
return arg;
}
const arrs = echoWithArr([1, 2, 3]);
所有有length属性的均可
interface IWithLength {
length: number;
}
function echoWithLength<T extends IWithLength>(arg: T): T {
console.log(arg.length);
return arg;
}
echoWithLength('str');
echoWithLength({length: 10});
echoWithLength([1, 2, 3]);
类和接口
// 限制只有一种数据类型的队列
class Queue<T> {
private data = [];
push(item: T) {
return this.data.push(item);
}
pop(): T {
return this.data.shift();
}
}
const queue = new Queue<number>();
queue.push(1);
console.log(queue.pop().toFixed());
const queue2 = new Queue<string>();
queue.push('str');
console.log(queue.pop().length);
interface KeyPair<T, U> {
key: T;
value: U;
}
let kp1: KeyPair<number, string> = {key: 123, value: 'str'};
let kp2: KeyPair<string, number> = {key: 'str', value: 123};
ts封装的大写类型
let arr: number[] = [1, 2, 3];
let arr2: Array<number> = [1, 2, 3];
interface写的函数类型
interface IPlus<T> {
(a: T, b: T): T;
}
function plus(a: number, b: number): number {
return a + b;
}
function connect(a: string, b: string): string {
return a + b;
}
const a: IPlus<number> = plus;
const b: IPlus<string> = connect;
类型别名
type aliases
function sum(x: number, y: number): number {
return x + y;
}
const sum2: (x: number, y: number) => number = sum;
type PlusType = (x: number, y: number) => number
function sum(x: number, y: number): number {
return x + y;
}
const sum2: PlusType = sum;
type NameResolver = () => string
type NameOrResolver = string | NameResolver // 联合类型
function getName(name: NameOrResolver) {
if (typeof n === 'string') {
return n;
}
else {
return n();
}
}
类型断言 as
type assertion
只能断言为定义的类型,若联合类型中未出现的类型断言会报错
function getLength(input: string | number): number {
const str = input as String;
if (str.length) {
return str.length;
}
else {
const number = input as Number
return number.toString().length;
}
}
function getLength(input: string | number): number {
if ((<string>input).length) {
return (<string>input).length;
}
else {
return input.toString().length;
}
}
声明文件
引用三方库时编译器给予提示
jQuery.d.ts
单独的声明文件
declare var jQuery: (selector: string) => any
但是三方库会提供声明文件,可进行单独安装
typesearch
现在的安装包一般都会带有type类型,所以无需特意安装