前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >typescript里一些有趣的点

typescript里一些有趣的点

作者头像
liulun
发布2019-07-02 17:32:03
3780
发布2019-07-02 17:32:03
举报
文章被收录于专栏:liulunliulun

联合类型

在原生的JS里,null和undefined经常会导致BUG的产生, 在ts里,你又想用null,又担心出错的时候 你可以考虑用联合类型,当某值可能为 number或null,你可以声明它的类型为number | null

代码语言:javascript
复制
let a : number | null = 2;

类型兼容

实现接口时,只要包含了接口要求的数据结构即可兼容这个接口

代码语言:javascript
复制
interface Person {
    firstName: string;
    lastName: string;
}
function greeter(person: Person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}
let user = { firstName: "Jane", lastName: "User" };
document.body.innerHTML = greeter(user);

面向对象

继承( extends关键字 ) public private protected static readonly get和set 都有,连namespace也有; 抽象类( abstract关键字 )

关于this

代码语言:javascript
复制
let deck: Deck = {
    // NOTE: The function now explicitly specifies that its callee must be of type Deck
    createCardPicker: function(this: Deck) {
        return () => {
           console.log(this)
        }
    }
}

指明this的类型必须是Deck

泛型

代码语言:javascript
复制
function identity<T>(arg: T): T {
    return arg;
}
let output = identity<string>("myString");  // type of output will be 'string'
//或者
let output = identity("myString");  // type of output will be 'string'

泛型方法、泛型类、泛型约束都有

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-06-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 联合类型
  • 类型兼容
  • 面向对象
  • 关于this
  • 泛型
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档