1、静态类型
interface Point {x: number;y: number;}const point: Point = {x: 3,y: 4};// 基础类型, boolean, number, string, void, undfined, symbol, nullconst count1: number = 123;const teacherName: string = 'xiaohong';// 对象类型const teacher1: {name: string;age: number;} = {name: 'xiaohong',age: 18};// 数组const numbers: number[] = [1, 2, 3];
2、函数注解和类型推断
- type annotation 类型注解, 我们来告诉 TS 变量是什么类型
- type inference 类型推断, TS 会自动的去尝试分析变量的类型
- 如果 TS 能够自动分析变量类型,我们就什么也不需要做了
- 如果 TS 无法分析变量类型的话,我们就需要使用类型注解 ```javascript // 自动推断返回值类型 function getTotal1(firstNumber: number, secondNumber: number) { return firstNumber + secondNumber; }
const total = getTotal1(1,2);
// 需要加类型注解 let count: number; count = 123;
// 自动推断为number类型 let countInference = 123;
<a name="vRTo5"></a># 3、函数类型```javascript// 有返回值function add(first: number, second: number): number {return first + second;}// 无返回值function sayHello(): void {console.log('hello');}// neverfunction errorEmitter(): never {while(true) {}}// 参数是对象function add({ first, second }: { first: number; second: number }): number {return first + second;}// 箭头函数const getNumber: (param: number) => number = (param: number) => {return param;};// 箭头函数泛型const func1: <T>(str: T) => T = <T>(str: T) => {return str;};
4、数组元组
// 数组const arr: (number | string)[] = [1, '2', 3];const stringArr: string[] = ['a', 'b', 'c'];const undefinedArr: undefined[] = [undefined];// type alias 类型别名type User = { name: string; age: number };// 元组 tupleconst teacherInfo: [string, string, number] = ['xiaohong', 'male', 18];const teacherList: [string, string, number][] = [['xiaohong', 'male', 19], ['sun', 'female', 26], ['jeny', 'female', 38]];
5、interface
interface Person {// readonly name: string; 只读name: string;age?: number;[propName: string]: any;say(): string;}const getPersonName = (person: Person): void => {console.log(person.name);};const person = {name: 'xiaohong',sex: 'male',say() {return 'say hello';},};getPersonName(person);
6、类
// private, protected, public 访问类型// public 允许我在类的内外被调用// private 允许在类内被使用// protected 允许在类内及继承的子类中使用// 构造函数class Person {// 传统写法// public name: string;// constructor(name: string) {// this.name = name;// }// 简化写法constructor(public name: string) {}}// 继承class Person {constructor(public name: string) {}}class Teacher extends Person {constructor(public age: number) {super('xiaoming');}}const teacher = new Teacher(28);console.log(teacher.age);console.log(teacher.name);
7、抽象类
abstract class Geom {width: number;getType() {return 'Gemo';}abstract getArea(): number;}class Circle extends Geom {getArea() {return 123;}}new Circle()
8、枚举
// 默认从0开始enum Status {OFFLINE = 1,ONLINE,DELETED}
9、泛型
function join<T, P>(first: T, second: P) {return `${first}${second}`;}join<number, string>(1, "1");join(1, "1"); // 可省略// 箭头函数泛型const func1: <T>(str: T) => T = <T>(str: T) => {return str;};// 类泛型class DataManager<T extends Item> {constructor(private data: T[]) {}getItem(index: string): T {return this.data[index];}}const data = new DataManager([{name: "xiaoming",},]);data.getItem('name');
10、联合类型
function formatPX(size: number | string) {// ...}formatPX(13); // okformatPX('13'); // ok
11、类型保护
类型保护允许你使用更小范围下的对象类型。
// typeoffunction doSome(x: number | string) {if (typeof x === 'string') {// 在这个块中,TypeScript 知道 `x` 的类型必须是 `string`console.log(x.substr(1)); // ok}x.substr(1); // Error: 无法保证 `x` 是 `string` 类型}// instanceofclass Foo {foo = 123;common = '123';}class Bar {bar = 123;common = '123';}function doStuff(arg: Foo | Bar) {if (arg instanceof Foo) {console.log(arg.foo); // okconsole.log(arg.bar); // Error}if (arg instanceof Bar) {console.log(arg.foo); // Errorconsole.log(arg.bar); // ok}}doStuff(new Foo());doStuff(new Bar());// ininterface A {x: number;}interface B {y: string;}function doStuff(q: A | B) {if ('x' in q) {// q: A} else {// q: B}}// 字面量类型保护type Foo = {kind: 'foo'; // 字面量类型foo: number;};type Bar = {kind: 'bar'; // 字面量类型bar: number;};function doStuff(arg: Foo | Bar) {if (arg.kind === 'foo') {console.log(arg.foo); // okconsole.log(arg.bar); // Error} else {// 一定是 Barconsole.log(arg.foo); // Errorconsole.log(arg.bar); // ok}}
