推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
caopi

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

  •  
  •   caopi · Oct 22, 2018 · 3910 views
    This topic created in 2786 days ago, the information mentioned may be changed or developed.

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

    8 replies    2018-10-22 15:32:56 +08:00
    caopi
        1
    caopi  
    OP
       Oct 22, 2018
    官方文档里将 typeof x === "number"抽象成一个函数,后面又说不必将他抽象成函数??
    caopi
        2
    caopi  
    OP
       Oct 22, 2018
    typescript 里面的 typeof 和 js 里面有什么区别吗
    ltoddy
        3
    ltoddy  
       Oct 22, 2018
    首先啊, 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  
       Oct 22, 2018
    @ltoddy typescript 并不是强类型,只是静态类型。
    maichael
        5
    maichael  
       Oct 22, 2018   ❤️ 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  
       Oct 22, 2018
    在 typescript 里面,typeof 分成两种情况,取决于值的用途。
    1. 作为变量使用,比如 const t = typeof A
    2. 作为类型使用,比如 type t = typeof A
    第一个和普通的 javascript 的 typeof 没有任何区别,第二个是 typescript 里的类型。
    kingwl
        7
    kingwl  
       Oct 22, 2018
    其实是两个部分
    1. type narrow (比如 typeof xxx === 'number' 和其他一大堆情况 )
    就是做类型推断
    2. type predicate (比如 xxx is Type)
    这个是允许一些你 type narrow 不过去的情况下, 自己断言一些类型
    caopi
        8
    caopi  
    OP
       Oct 22, 2018
    @maichael 明白了,谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2681 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 15:38 · PVG 23:38 · LAX 08:38 · JFK 11:38
    ♥ Do have faith in what you're doing.