ts-基础2

接口

//对象类型
interface Interface1 {
    label: string; // 必填属性
    value?:number; // 可选属性
    readonly y: number; // 必填 只读属性 仅在对象刚创建时可以修改值
    readonly x?: number;// 可选 只读属性
}
// 使用情景1
let obj:Interface1 = {
    label:'label',
    y:1
};
// json.y = 2;  y是只读属性 不能再次修改

// 使用情景2
function func1(params:Interface1){
    //...
}
func1({label:'label',y:1})
// 使用情景2.1
func1({label:'label',y:1,
    // z:2 // 不能传其他参数 因为 IParams 接口没有定义其他参数
})
// 解决办法1
func1({label:'label',y:1,z:2 } as Interface1);
// 解决办法2
func1(<Interface1>{label:'label',y:1,z:2});
// 解决办法3
let p1 = {label:'label',y:1,z:2}
func1(p1)
// 解决办法4
// 增加索引签名 // 不推荐
interface Interface1 {
    [name:string]:any
}
func1({label:'label',y:1,z:2})

//函数类型
interface Interface2 {
    (code1: string, code2: string): boolean;
}
let func2:Interface2 = (name1:string,name2:string):boolean => true;

// 类类型 混合类型
interface Interface3 {
    // new (hour: number, minute: number):any, 构造方法属于静态方法 需要特殊使用
    name:string,   // 属性
    setName():void,// 方法
    getName(name:string):string,// 方法
}
// 使用
class Clock implements Interface3 {
    name!:string;
    constructor(){}
    setName(){};
    getName(name:string){
        return name;
    }
    setAge(){};
}

let obj3:Interface3 = {
    name:'a',
    getName:(name:string) => name,
    setName(){}
};

// 索引签名
// 数字索引
interface Interface4{
    [type:number]:string
}
let arr1:Interface4 = ['a','b'];
console.log(arr1[0]);

// 字典模式 确保所有属性的返回值匹配
interface Interface5 {
    [index: string]: number;
    length: number;    // 可以,length是number类型
    // name: string    // 错误,`name`的类型与索引类型返回值的类型不匹配
}
// 只读索引
interface Interface6 {
    readonly [index: number]: string;
}
let arrList1: Interface6 = ["haha", "hbhb"];
// arrList1[2] = "hchc"; // 错误


// 接口继承
interface Interface7{
    name:string
};
interface Interface8{
    age:number
};
// 继承
interface Interface9 extends Interface7{
    sex:number
}
// 继承多个
interface Interface10 extends Interface7,Interface8{
    height:number
}
let json44:Interface9 = {
    name:'1',
    sex:1,
}
// 接口继承类
class Class1 {
    private code:any
}
interface Interface11 extends Class1{
    fn1(str:string):void
}
class Class2 extends Class1 implements Interface11 {
    fn1(str: string): void {
        
    }
}

泛型

function fun6<T,B,C>(
    age:T,   // 任意类型
    label:B[], // 数组类型1
    value:Array<C> // 数组类型2
):B[] {return label;}
// 使用
let fun6output = fun6<string,number,boolean>('18',[1],[true]); 

// 泛型接口
function identity<T>(arg: T): T {
    return arg;
}
let myIdentity1: <T>(arg: T) => T = identity;
let myIdentity2: {<T>(arg: T): T} = identity;

interface IFX1{
    <T>(code:T):T // 只有这里有泛型
}
let func71:IFX1 = identity;

interface IFX2<T>{ // 泛型参数
    (code:T):T
}
let func72:IFX2<string> = identity;

// 泛型类
// 泛型类指的是实例部分的类型 静态属性不能使用泛型类型
class Cl1<T> {
    // static code:T; 错误
    setName(name:T):T{
        return name;
    }
}
let c1 = new Cl1<number>();
c1.setName(1);

// 7.3 泛型约束
interface IHasLength {
    length: number;
}
function fun8<T extends IHasLength>(arg:T):T{
    console.log(arg.length);  
    return arg;
}
fun8('a') // 只能传如包含length属性的参数 

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
    return obj[key]
}
let json7 = { a: 1, b: 2, c: 3, d: 4 };
getProperty(json7, "a"); // okay
// getProperty(x, "m"); // 错误

类型

// 交叉类型 & 是将多个类型合并为一个类型
interface I1 {
    name:string,
    height:string,
    // width:string,
}
interface I2 {
    age:number,
    height:string,
    // width:number,
}

let test:I1 & I2 = {
    name:'haha',
    height:'height', // 同名 同类型的 可以存在
    age:12,
    // width:never,   width是never类型 所以交叉类型不能有同名不同类型的
};
// 联合类型
let test1:string | number | boolean = '1';

// 复杂类型 需要类型保护和区分类型
interface IUnionCode1 {
    name:string,
    sex:string,
}
interface IUnionCode2 {
    age:number,
    sex:string,
}

let unionCode:IUnionCode1 | IUnionCode2 = {
    name:'asadf',
    age:1,
    sex:'b'
};
// console.log(unionCode.name) // 会报错 因为name不是共有成员 需要类型断言
// 解决办法1
console.log((<IUnionCode1>unionCode).name);   // 使用断言类型
console.log((unionCode as IUnionCode1).name); // 使用断言类型
// 解决办法2
function isCode1(arg: IUnionCode1 | IUnionCode2): arg is IUnionCode1 {
    return (<IUnionCode1>arg).name !== undefined;
}
if(isCode1(unionCode)){ // 通过此方法
    console.log(unionCode.name); // 这里会确定是IUnionCode1
} else {
    console.log(unionCode.age);  // 这里会确定是IUnionCode2
}
// 解决办法3 保护机制  typeof 
// typename 取值只能为string number boolean symbol 
interface I5 { 
    name:string | number
};
let test3:I5 = {
    name:'123'
};
if(typeof test3.name === 'number'){
    console.log(test3.name.toFixed(2));
} 

// 解决办法4 instanceof 类中的方法
// 通过构造函数来细化类型 
class TClass1 {

}
let test4 = new TClass1();
if(test4 instanceof TClass1){
    //...
}
// 解决办法5   null的处理
// if 
function test5(name:string | null):string{
    if(name == null){
        name = 'default';
    }
    return name;
}
// || 短路
function test6(name:string | null):string{
    return name || 'default';
}
// 解决办法6 !后缀 表示排除null undefined 所以必须有值
function test7(name:string | null):string{
    console.log(name!.charAt(0));
    console.log(name?.charAt(0));
    return name || 'default';
}

// 类型别名
/*
    别名和接口
    别名不能被extends 和 implemenets 所以应该尽量使用接口代替类型别名
    如果你无法通过接口来描述一个类型并且需要使用联合类型或元组类型,这时通常会使用类型别名。
*/ 
type Itype1 = string;  // 给原始类型起别名没什么用
type Itype2 = () => string;
type Itype3 = Itype1 | Itype2; 
function test8(n: Itype3): Itype1 {
    if (typeof n === 'string') {
        return n;
    }
    else {
        return n();
    }
}
// 支持泛型
type Container<T> = { value: T };
type Tree<T> = { // 同接口 可以引用自己
    value: T;
    left: Tree<T>;
    right: Tree<T>;
}

interface info {
    name:name,
}
type name = 1 | 'code2' ;
function test9(name:info){
    if(name.name == 1){
        console.log(name);
    } else if(name.name == 'code2'){
        console.log(name);
    } else {
        console.log(name);
    }
}
test9({
    name:1 // 传参不能为 name 不包括的值
}); 
// 枚举成员类型
interface It1 {
    name:'haha',
    age:number
}
interface It2 {
    name:'hehe',
    width:number
}
interface It3 {
    name:'hchc',
    height:number
}
interface It4 {
    name:'hbhb',
}
type name1 = It1 | It2 | It3 | It4;
function t1(params:name1):number{
    switch (params.name) {
        case "haha": return params.age * params.age;
        case "hehe": return params.width * params.width;
        case "hchc": return Math.PI * params.height * 2;
        default:return 1; // 若忘记了某个case 这里可以增加错误处理
    }
}
t1({name:'hbhb'});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值