在cmd上显示
npm install -g ts-node
npm install -g @types/node
执行命令
//编译成原生js
tsc demo.ts
ts-node demo.ts
初始化typescript
tsc --init
interface接口
var getPersonName = function (person) {
console.log(person.name);
};
var setPersonName = function (person, name) {
person.name = name;
};
var person = {
name: "dell",
say: function () {
return "hello";
},
//增加教师
teach: function () {
return "teach";
}
};
getPersonName(person);
setPersonName(person, "lee");
var User = /** @class */ (function () {
function User() {
this.name = "Mel";
}
User.prototype.say = function () {
return "12";
};
return User;
}());
var say = function (word) {
return word;
};
继承
class Person {
name = "Anna";
getName() {
return this.name;
}
}
class Teacher extends Person {
getTeacherName() {
return "Teacher";
}
getName() {
return super.getName() + " lee";
}
}
const teacher = new Teacher();
console.log(teacher.getName());
constructor
//constructor
class Person {
public name: string;
constructor(name: string) {
this.name = name;
}
}
const person = new Person("lee");
console.log(person.name);
简便写法
class Person {
// public name: string;
constructor(public name: string) {
// this.name = name;
}
}
const person = new Person("lee");
console.log(person.name);
class Person {
constructor(public name: string) {}
}
class Teacher extends Person {
constructor(name: string, public age: number) {
super(name);
}
}
const teacher = new Teacher("lucky", 28);
console.log(teacher.age);
console.log(teacher.name);
setter 和 getter
class Person {
constructor(private _name: string) {}
get name() {
return this._name + " lee";
}
set name(name: string) {
const realName = name.split(" ")[0];
this._name = realName;
}
}
const person = new Person("kenny");
console.log(person.name);
person.name = "dell lee";
console.log(person.name);
静态函数,只生成一个对象
class Demo {
private static instance: Demo;
private constructor(private _name: string) {}
static getInstance(name: string) {
if (!this.instance) {
this.instance = new Demo(name);
}
return this.instance;
}
get name() {
return this._name;
}
}
const demo1 = Demo.getInstance("nana");
const demo2 = Demo.getInstance("nana too");
console.log(demo1.name);
console.log(demo2.name);
readonly只能读不能改
class Person{
public readonly _name;
constructor(name:string) {
this._name=name
}
}
抽象类
abstract class Geom {
width: number = 0;
getType() {
return "Geom";
}
abstract getArea(): number;
}
class Circle extends Geom {
getArea(): number {
return 123;
}
}
接口继承
interface Person {
name: string;
}
interface Teacher extends Person {
name: string;
teachingAge: number;
}
interface Student {
name: string;
age: number;
}
const getUserInfo = (user: Person) => {
console.log(user.name);
};
const teacher = {
name: "dell",
};
const student = {
name: "lee",
age: 18,
};
getUserInfo(teacher);
getUserInfo(student);