• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

typescript基础篇拾遗

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

1、null或者undefined赋值

(1)将变量定义为联合类型

let num: number | undefined | null = 123

(2)将tsconfig的strictNullChecks设置为false。

 

 

 2、接口定义

interface List {
    // 只读属性
    readonly id: number;
    name: string;
    // 可选属性
    age?: number;
    // 函数
    doSomething(): void;
}

 

3、函数重载

// 不定义实现
function add8(...rest: number[]): number;
// 不定义实现
function add8(...rest: string[]): string;
// 实现
function add8(...rest: any[]) {
    let first = rest[0];
    if (typeof first === 'number') {
        return rest.reduce((pre, cur) => pre + cur);
    }
    if (typeof first === 'string') {
        return rest.join('');
    }
}

 

4、抽象类

// 抽象类
// 只能被继承
// es是没有的,ts才有
abstract class Animal {
    eat() {
        console.log('eat')
    }
    // 抽象方法 没有实现体 只能在子类实现
    abstract sleep(): void
}

 

5、静态属性和静态方法都有

class Dog extends Animal {
    // name是string
    constructor(name: string) {
        super()
        this.name = name
        this.pri()
    }
    // 也可以是可选属性
    public name?: string = 'dog'
    run() {}
    private pri() {}
    protected pro() {}
    public pro2() {}
    readonly legs: number = 4
    // 静态属性 也可以有静态方法
    // 静态属性和方法是可以被继承的
    static fs(){
    }
    static food: string = 'bones'
    sleep() {
        console.log('Dog sleep')
    }
}

 

6、构造函数上的public属性会自动变成public属性

class Husky{
    // public 属性变成实例属性
    constructor(public name: string) {
    }
    say(){
        console.log(this.name)
    }
}
let aa = new Husky('yu')
aa.say();

编译后的代码为:

 

 

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
使用TypeScript开发微信小程序的方法发布时间:2022-07-18
下一篇:
8、TypeScript模块发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap