开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 2 天,点击查看活动详情
类型断言
-
可以手动指定一个类型
1.变量 as 类型
2.<类型>变量
function getLength(x:string|number):number{ if((x as string).length){ return (<string>x).length }else{ return x.toString().length } }(window as any).a = 10;
类型别名
通过type去定义
type s=string
let str:s ;
str = "234"
console.log(str)
type all = string | boolean | number
type stringName = "tom" | "lucy" | "jack"
let x:stringName = "tom"
console.log(x)
元组
合并了不同类型的对象
let Tarr:[string,number]=["ls",123]
console.log(Tarr)
枚举
enum NumType{
one=1,//没有赋值,默认为0,后面的值不设置,默认递增
two,
three,
four,
}
console.log(NumType)
根据前面的值默认加1
可以通过名称拿取值,可以通过值拿取名称
-
枚举有两种类型:常数项和计算所得项
计算所得项
enum Color{ red, blue="blue".length, } console.log(Color)计算所得项后面不能接未赋值的枚举项
-
常数枚举
const enum Obj{ O,B,J }常数枚举和枚举的区别,会在编译阶段删,并且不能包含计算成员
类
比Es6 class 增加了新的功能
class Person{
age:number
constructor(age:number) {
this.age = age;
}
sayHi(name:string){
console.log("hello "+name)
}
}
let p = new Person(1)
p.sayHi("ls")
-
继承
class Animal{ name:string age:number constructor(name:string,age:number) { this.name = name; this.age = age; } sayHi(str:string){ console.log("hello "+str); } } class Dog extends Animal{ constructor(name:string,age:number) { super(name,age); } sayHi(str: string) { super.sayHi(str); } } let a = new Dog("hhh",12); -
存取器
class Name{ firstName:string lastName:string constructor(firstName:string,lastname:string) { this.firstName = firstName this.lastName = lastname } get FullName(){ return this.firstName+"-"+this.lastName } set fullName(value){ console.log(value) } } const N = new Name("l","s") N.fullName = "hhh" console.log(N) -
静态成员
类本身调用的属性和方法
class Name { static sayHi() { console.log("hh"); } } Name.x = "HHH"; console.log(Name.x); Name.sayHi(); -
修饰符
public,private,protected
不写默认是public
public修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是public的private修饰的属性或方法是私有的,不能在声明它的类的外部访问protected修饰的属性或方法是受保护的,它和private类似,区别是它在子类中也是允许被访问的