学无先后,达者为师

网站首页 编程语言 正文

typescript中的泛型(genericParadigm)、interface、extends、constructor

作者:web半晨 更新时间: 2022-06-06 编程语言
function fnAny(a: any): any {
    return a;
}

console.log('number:', fnAny(10));
// number: 10
console.log('string:', fnAny('半晨'));
// string: 半晨

// 在定义函数或是类时,如果遇到类型不明确就可以使用泛型
// T是任意字母,只是个代表而已,也就是变量的意思
function fn<T>(a: T): T {
    return a;
}

// 可以直接调用具有泛型的函数
// 不指定泛型,TS可以自动对类型进行推断
console.log('number:', fn(24));
// number: 24
// 指定泛型
console.log('string:', fn<string>('hello'));
// string: hello

// 泛型可以同时指定多个
function fn2<T, K>(a: T, b: K): T {
    console.log('b:', b);
    // b: hello
    return a;
}
console.log('a:', fn2<number, string>(123, 'hello'));
// a: 123

// 接口
interface Inter {
    length: number;
}

// T extends Inter 表示泛型T必须是Inter的实现类(子类)
function fn3<T extends Inter>(a: T): number {
    return a.length;
}

class MyClass<T>{
    name: T;
    constructor(name: T) {
        this.name = name;
        console.log('name:', this.name);
        // name: 半晨
    }
}

new MyClass<string>('半晨');




原文链接:https://blog.csdn.net/weixin_51157081/article/details/122313064

栏目分类
最近更新