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

typescript 的编译选项中 如何 禁止 类型 自动转换

  •  
  •   ruandao · 2019-09-16 14:38:55 +08:00 · 2894 次点击
    这是一个创建于 1655 天前的主题,其中的信息可能已经有所发展或是发生改变。

    譬如

    type UserId = string;

    然后 要求 UserId 和 string 是两种不同的类型,需要手动转换才行

    项目是 react, 有个配置文件 tsconfig.json, 里面已经开启了 "alwaysStrict": true

    但是好像没效果

    8 条回复    2019-09-16 17:18:27 +08:00
    Austaras
        1
    Austaras  
       2019-09-16 14:49:11 +08:00   ❤️ 1
    没有办法, typescript 是 structural typing,只要签名对的就是一个东西
    另外要开严格模式是设置 strict, alwaysStrict 是总是生成 use strict 的 js
    blindie
        2
    blindie  
       2019-09-16 15:04:56 +08:00 via Android   ❤️ 1
    啥意思? type UserId = string 意思就是 UserId 是 string 的 alias。本来就是同一个东西 又要要求 UserId 和 string 是两种不同类型????那就不要用 type a = b
    noe132
        3
    noe132  
       2019-09-16 15:06:55 +08:00   ❤️ 1
    type 只是 alias。
    如果你要区分 UserId 和 string,建议给 userId 添加一个包装对象
    maomaomao001
        4
    maomaomao001  
       2019-09-16 15:41:29 +08:00   ❤️ 1
    类似这种吧,完全没有任何关系的两个类,只要结构能兼容,就可以互相赋值。这个应该是没有办法的

    ```

    class C1 {
    cc = 100
    }

    class C2 {
    cc = 123
    }

    let xx:C1;

    xx = new C2(); //多么希望这里报错!!!!



    ```
    banxi1988
        5
    banxi1988  
       2019-09-16 17:10:11 +08:00   ❤️ 1
    哈哈,楼主估计是从 Go 过来的. Go 里面 type 这样操作一下是两种类型了.
    但是在 TypeScript 中这样不行. 这相当于 C 里面的 typedef. 不会报错的,因为没有定义一种新类型.
    momocraft
        7
    momocraft  
       2019-09-16 17:17:47 +08:00   ❤️ 1
    #6 的回答也适合#4, 总之就是假装类型里有些不 structural compatible 的东西
    kingwl
        8
    kingwl  
       2019-09-16 17:18:27 +08:00   ❤️ 2
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5489 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 09:01 · PVG 17:01 · LAX 02:01 · JFK 05:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.