npm i typescript -g
tsc main.ts
tsc -w main.ts
let a: boolean = true;
let b: boolean = false;
let a: number = 1;
let a: string = "Hello World";
相当于原生Javascript的定义,不限制类型。
let a: any = 1;
let b: any = "Hello World";
let c: Array<any> = [1, 'a', true];
let a: Array<number> = [1, 2, 3];
let b: number[] = [1, 2, 3];
let c: string[] = ['a', 'b', 'c'];
限制数组长度和对应下标的数据类型。
let a: [number, string, boolean] = [1, 'a', true];
let a: object = {};
enum arr1 {a, b, c}
enum arr2 {a = 10, b, c}
console.log(arr1.b, arr2.b); //会输出1和11
常用于定义不返回值的函数。
let a: void = null;
let b: void = undefined;
function c(): void {
alert(1);
}
let a: Function = function() {}
给函数的参数和返回值定义数据类型。
function hello(name: string): string {
return "Hi " + name;
}
class Person {
name: string;
sex: string;
age: number;
constructor(name: string, sex: string, age: number) { // 构造函数,用于接受传参
this.name = name;
this.sex = sex;
this.age = age;
}
say() {
return "My name is " + this.name;
}
}
let a = new Person("xiaoming", "girl", 14);
console.log(a.say());
class Student extends Person {
major: string;
constructor(name: string, sex: string, age: number, major: string) {
super(name, sex, age); // 父级类的constructor
this.major = major;
}
studentSay() { // 不能与父级类里已有的方法同名
return this.major;
}
}
限制类的属性和方法的权限
interface User {
name: string, // 必填
age: number, // 必填
gender?: string, // 可选
[key: string]: any // 其他属性
}
function createUser(data: User) {
console.log(data);
}
接口限制函数
interface UserFunction {
(name: string, age: number): void;
}
let createUser: UserFunction = (name, age) => {
console.log(name, age);
}
接口限制类
interface personInterface {
name: string; // 必填
age?: number; // 可选
greeting(): string; // 必填
}
class Student implements personInterface {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greeting(): string {
return 'My name is ' + this.name;
}
}