TS
TypeScript用法类型定义任意类型联合类型,多个类型定义数组接口可选属性
函数类型类型别名 type联合类型别名类修饰符泛型!!!枚举元组
TypeScript用法
安装 cnpm install -g typescript查看版本 tsc -v编译 tsc 加文件名.ts (比如:tsc deom.ts)
类型定义
let str
:string = "10"
let num
:number = 10
let nul
:null = null
let unde
: undefined
= undefined
let bool
:boolean = true
任意类型
let anys
:any = "10"
anys
= 10
anys
= true
anys
= null
联合类型,多个类型
let more
: number | string;
more
= 10
more
= "哈哈哈哈"
定义数组
let arr
: number[] = [1, 2, 3, 4];
let arr2
: string[] = ["1", "2", "3"];
let arr3
: any[] = ["1", 1, true, [66]];
接口
简称约束
interface Person {
name
:string,
age
:number,
}
let obj
:Person
= {
name
:"1",
age
:1,
}
可选属性
interface Person2 {
name
:string,
age
?:number,
}
let obj2
:Person2
= {
name
:"1"
}
函数类型
function fun(x
: number, y
: number): string {
return "88888";
}
fun(1, 2);
function fun2(x
: number = 30, y
?: number): void {
console.log(x
, y
);
}
fun2();
类型别名 type
type num
= number
let n2
:num
= 10
联合类型别名
type multi
= string | number[]
let x1
:multi
= "哈哈哈"
let x2
:multi
= []
类
class Animal {
name
:string;
constructor(name
){
this.name
= name
}
eat(){
return "吃肉"
}
}
class Dog extends Animal{
constructor(name
){
super(name
)
}
say(){
return this.name
+ " " + this.eat()
}
}
let dog
= new Dog("aaa")
dog
.say()
修饰符
public 可以在任何地方被访问到,默认就是公共的protected 自己和子类可以访问private 任何人都不能访问(包括子类),只能在自己内部用
class Animal {
name
: string;
constructor(name
) {
this.name
= name
;
}
eat() {
return "吃肉";
}
}
class Dog extends Animal {
constructor(name
) {
super(name
);
}
say() {
return this.name
+ " " + this.eat();
}
}
let dog
= new Dog("aaa");
dog
.say();
class Animal2 {
static eat() {
return "吃肉";
}
static Name
: string = "123";
}
Animal2
.eat();
Animal2
.Name
;
class A3 {
public static Name
= "123";
private static eat() {
return "吃肉";
}
}
A3.Name
;
class Yy {
protected Yeat() {
return "吃肉";
}
eat2() {
return "吃鱼";
}
}
class Lwh extends Yy {
constructor() {
super();
}
fun() {
return this.Yeat();
}
}
let yy
= new Yy();
let lwh
= new Lwh();
lwh
.fun();
泛型!!!
枚举是指在定义函数、接口或类时候,不先指定具体的类型,而在使用时再指定它的类型 T表示泛型变量 表示任何类型 这样也可以,不一定要用 T <这里里面的值表示任何类型>
function hello
<T>(name
:T):T{
return name
}
hello("6666")
1.泛型的约束
extends
interface Length
{
length
:number
}
function hello2
<S extends Length>(name
:S){
}
hello2("123")
hello2([123])
2.指定泛型 ()
function yy
<T>(name
,age
:T){
console.log(name
);
console.log(age
);
}
yy
<number>("张三",55)
3.泛型在类中运用()
class A3<T>{
n
:T
constructor(num
:T){
this.n
= num
}
add(x
:T):T{
return x
}
}
let a3
= new A3<number>(1)
枚举
给某个值做一个标记
enum LWH {
success
= 200,
fail
= 500,
}
元组
指定数组中元素的类型
let tuple
: [number, string, boolean] = [100, "200", true];