V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
caopi
V2EX  ›  JavaScript

最近在看 typescript,看到类型保护不太理解

  •  
  •   caopi · 2018-10-22 14:12:43 +08:00 · 3337 次点击
    这是一个创建于 1985 天前的主题,其中的信息可能已经有所发展或是发生改变。

    typeof 和 instanceof 为何需要写在函数里面呢

    8 条回复    2018-10-22 15:32:56 +08:00
    caopi
        1
    caopi  
    OP
       2018-10-22 14:21:25 +08:00
    官方文档里将 typeof x === "number"抽象成一个函数,后面又说不必将他抽象成函数??
    caopi
        2
    caopi  
    OP
       2018-10-22 14:24:37 +08:00
    typescript 里面的 typeof 和 js 里面有什么区别吗
    ltoddy
        3
    ltoddy  
       2018-10-22 14:31:48 +08:00
    首先啊, typescript 是强类型的, 也就是每个变量他的类型是知道的, 或者你声明变量的类型, 或者通过 typescript 的类型推导, 每个变量有明确的类型, 那么类型你都知道, typeof 一个变量不就是有毛病嘛.

    借用官网教程的一段代码:

    ```
    function reverse(x: number): number;
    function reverse(x: string): string;
    function reverse(x: number | string): number | string {
    if (typeof x === 'number') {
    return Number(x.toString().split('').reverse().join(''));
    } else if (typeof x === 'string') {
    return x.split('').reverse().join('');
    }
    }
    ```

    这里用了 typeof, 是为了函数重载.
    maichael
        4
    maichael  
       2018-10-22 14:34:11 +08:00
    @ltoddy typescript 并不是强类型,只是静态类型。
    maichael
        5
    maichael  
       2018-10-22 14:43:14 +08:00   ❤️ 1
    实际上文档里面说的重点在于静态类型推导这一问题,在函数 padLeft 里,padding 是 string 或者 number 类型,如果 typescript 没有足够的智能识别变量的类型,比如它即便通过了 if(typeof padding === "number"),它仍旧认为 padding 是 string|number 类型,那么 Array(padding + 1).join(" ") + value 就会有问题。所以需要通过 x is number 来将 padding 转化成 number,但 typescript 足够智能,所以不会有这问题。
    maichael
        6
    maichael  
       2018-10-22 14:47:48 +08:00
    在 typescript 里面,typeof 分成两种情况,取决于值的用途。
    1. 作为变量使用,比如 const t = typeof A
    2. 作为类型使用,比如 type t = typeof A
    第一个和普通的 javascript 的 typeof 没有任何区别,第二个是 typescript 里的类型。
    kingwl
        7
    kingwl  
       2018-10-22 14:57:40 +08:00
    其实是两个部分
    1. type narrow (比如 typeof xxx === 'number' 和其他一大堆情况 )
    就是做类型推断
    2. type predicate (比如 xxx is Type)
    这个是允许一些你 type narrow 不过去的情况下, 自己断言一些类型
    caopi
        8
    caopi  
    OP
       2018-10-22 15:32:56 +08:00
    @maichael 明白了,谢谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2849 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 13:41 · PVG 21:41 · LAX 06:41 · JFK 09:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.