首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【译】Typescript 3.7 常用新特性一览

【译】Typescript 3.7 常用新特性一览

作者头像
西南_张家辉
发布2021-02-02 10:20:09
7910
发布2021-02-02 10:20:09
举报
文章被收录于专栏:张家辉的树屋张家辉的树屋

相关文章导航

写在最前面

  • 3.7, 其实至今 3.9 beta 已经发布,有兴趣的同学可以研究一下,这里列举几个常用的 3.7 的特性。

大部分自译,少量借用 google 翻译(ps: google 翻译质量还不错),需要了解和使用 typescript 的看官网学习是非常好的,特别是英文文档写得非常不错。

可选链式运算符

常用新特性 1

  • ?. 的使用
// Before
if (foo && foo.bar && foo.bar.baz) {
    // ...
}

// After-ish
if (foo?.bar?.baz) {
    // ...
}

直接看代码,我们在使用链式调用的时候一般都会检测链式的存在问题,这里我们的 ==?== 帮我们完成了这件事儿。下面看官方的解释

// 使用 ?.
let x = foo?.bar.baz();

// 执行逻辑编译如下
let x = (foo === null || foo === undefined) ?
    undefined :
    foo.bar.baz();
    
/* 当 foo 不存在或者未定义的时候,直接返回 undefined,这个时候 x = undefined

this is a way of saying that when foo is defined, foo.bar.baz() will be computed; but when foo is null or undefined, stop what we’re doing and just return undefined.”

常用新特性 2

  • ?? 运算符
let x = foo ?? bar();

这是一种新的表示值foo“存在”时将被使用的方式;但是当它是null或时undefined,去计算 bar()

同样,以上代码等效于以下代码。

let x = (foo !== null && foo !== undefined) ?
    foo :
    bar();

type 的扩展使用

常用新特性 3

type Json =
    | string
    | number
    | boolean
    | null
    | JsonObject
    | JsonArray;

interface JsonObject {
    [property: string]: Json;
}

interface JsonArray extends Array {}
  • ts 3.7 实现
type Json =
    | string
    | number
    | boolean
    | null
    | { [property: string]: Json }
    | Json[];

我们不必再借用 interface 来组装一个 Json 数组对象,可以直接借由{ } 包装实现。

断言功能的扩展

  • throw如果发生意外情况,则有一组特定的函数会出错。它们被称为“断言”功能。例如,Node.js为此有一个专用功能assert。
assert(someValue === 42);

在此示例中,如果someValue不等于42,assert则将抛出AssertionError。
  • JavaScript中的断言通常用于防止传入不正确的类型。例如,
function multiply(x, y) {
    assert(typeof x === "number");
    assert(typeof y === "number");

    return x * y;
}

不太好的是,在TypeScript中,这些检查永远无法正确编码。对于松散类型的代码,这意味着TypeScript的检查较少,而对于稍微保守的代码,则通常迫使用户使用类型断言。

function yell(str) {
    assert(typeof str === "string");

    return str.toUppercase();
    // Oops! We misspelled 'toUpperCase'.
    // Would be great if TypeScript still caught this!
}
复制代码
  • 替代方法是改写代码,以便语言可以对其进行分析,但这并不方便。
function yell(str) {
    if (typeof str !== "string") {
        throw new TypeError("str should have been a string.")
    }
    // Error caught!
    return str.toUppercase();
}

解决方案,最终,TypeScript的目标是以最小的破坏性方式键入现有的JavaScript结构。因此,TypeScript 3.7引入了一个称为“断言签名”的新概念,可以对这些断言函数进行建模。

第一种类型的断言签名对Node assert函数的工作方式进行建模。它确保在包含范围的其余部分中,无论检查什么条件都必须为真。

function assert(condition: any, msg?: string): asserts condition {
    if (!condition) {
        throw new AssertionError(msg)
    }
}
复制代码

asserts condition表示,condition如果assert返回则传递给参数的任何内容都必须为true (因为否则会引发错误)。这意味着对于其余范围,该条件必须是真实的。举个例子,使用这个断言函数意味着我们确实证实了 yell 的例子。

function yell(str) {
    assert(typeof str === "string");

    return str.toUppercase();
    //         ~~~~~~~~~~~
    // error: Property 'toUppercase' does not exist on type 'string'.
    //        Did you mean 'toUpperCase'?
}

function assert(condition: any, msg?: string): asserts condition {
    if (!condition) {
        throw new AssertionError(msg)
    }
}
复制代码

断言签名的另一种类型不检查条件,而是告诉TypeScript特定的变量或属性具有不同的类型。

function assertIsString(val: any): asserts val is string {
    if (typeof val !== "string") {
        throw new AssertionError("Not a string!");
    }
}
复制代码

参考

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 写在最前面
  • 可选链式运算符
    • 常用新特性 1
      • 常用新特性 2
      • type 的扩展使用
        • 常用新特性 3
        • 断言功能的扩展
        • 参考
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档