//类型别名 type
type n = number;
function f1(x:n):n{
return x;
}
var n2:n =10;
//联合类型别名
type a = string | number[];
var c1:a = 'ccc';
var c2:a = [1,2,3];
var c3:a = 11; //err c3的类型里面没有number类型
//类 class
//首字母大写
//类(class):定义了一件事物的抽象特点,包含它的属性和方法
class A { //定义类,名称为A
}
//ES5
function Person (name,age){
this.name = name;
this.age = age;
}
Person.prototype.say = function(){
return this.name;
}
var p1 = new Person('cc',10);
p1.name; //cc
p1.say();
//ES6
//一个类必须有constructor
//class ===> A {} === class A {constructor(){}}
class Person2 {
name:string; //提前定义值类型
age:number;
constructor(name,age){
this.name = name;
this.age = age;
}
say(){
return this.name;
}
}
var p2 = new Person2('bb',12);
//类的继承
//动物类
class Animal {
name:string;
constructor(name){
this.name = name;
}
eat(){
return '吃肉'
}
}
//继承
class Cat extends Animal{
constructor(name){
super(name);
}
say(){
return this.name+' '+ this.eat() //调用父类的属性和方法
}
}
var c = new Cat('vvv');
c.say()
//static 静态方法 修饰符 不需要实例化 可以直接通过类来调用
class Animal2 {
static url:string = "acc";
static eat(){ //添加修饰符
return '吃肉'
}
eat2 (){
return '吃素'
}
}
var a1 = new Animal2 ();
// a1.eat() //err
Animal2.eat(); //不需要实例化
Animal2.url;
// Animal2.eat2(); //err
//修饰符
//public 修饰的属性或方法是共有的,可以在任何地方被访问到,默认所有属性和方法都是public的
//private 修饰的属性或方法是私有的,不能在声明它的类的外部访问
//protected 修饰的属性或方法是收到保护的,它和private类似,区别是它在子类中也是允许被访问的
class A2 {
name:string;
constructor(name){
this.name = name
}
public static url:string = 'ccc';
public eat(){
return 'eat meat'
}
eat2(){
return 'abstain from eating meat'
}
}
//private 修饰的属性或方法是私有的,不能在声明它的类的外部访问
class A3 {
private eat(){
return 'eat meat'
}
public eat2(){
return 'adstain from eating meat'
}
}
var a3 = new A3();
a3.eat2();//正常访问
a3.eat();//err 访问错误,但不影响正常编译
//protected 修饰的属性是受到保护的,它和private类似,区别是它在子类中允许被访问
class A4 {
protected eat(){
return 'eat meat'
}
private eat2(){
return 'abstain from eating meat'
}
public eat3(){
return 'polyphagia'
}
}
class A5 extends A4 {
constructor(){
super()
}
fun(){
return this.eat();//子类的内部是可以访问的
}
fun2(){
return this.eat2(); //子类也不能访问
}
}
var a4 = new A4();
a4.eat();//err
a4.eat2();//err
a4.eat3()
//类的类型
class A6 {
name:string;
constructor(name){
this.name = name;
}
eat():string{
return 'eat meat'
}
eat2(n:string):number{
return 1
}
}
//类的接口实现
//接口
interface Obj{
name:string,
age?:number,
say():string
}
//类的接口实现 implements--实现
class A7 implements Obj{
name:string;
age:number;
// age:number[]; //err age是可选属性 数据类型也受到接口的约束
// name:number; //err name的类型受到接口的约束
constructor(name){
this.name = name;
}
say(){
return '1'
}
say2(){
return 1
}
}
//demo
//定义门 公共类
class Door {
}
//定义防火门 ,门的子类
class FireDoor extends Door implements Alertor {
sound(){
}
}
// 报警功能 接口
interface Alertor {
sound();
}
//灯 接口
interface Light {
lightOn();
lightOff();
}
//车 类
class Car implements Alertor,Light {
sound(){
}
lightOn(){
}
lightOff(){
}
}
//车类受到Alertor和Light接口的约束,所以sound(),lightOn(),lightOff()这三个方法必须得有
TS-class类+类的继承+修饰符
最新推荐文章于 2024-06-10 00:15:00 发布