譬如
type UserId = string;
然后 要求 UserId 和 string 是两种不同的类型,需要手动转换才行
项目是 react, 有个配置文件 tsconfig.json, 里面已经开启了 "alwaysStrict": true
但是好像没效果
没有办法, typescript 是 structural typing,只要签名对的就是一个东西
另外要开严格模式是设置 strict, alwaysStrict 是总是生成 use strict 的 js
啥意思? type UserId = string 意思就是 UserId 是 string 的 alias。本来就是同一个东西 又要要求 UserId 和 string 是两种不同类型????那就不要用 type a = b
type 只是 alias。
如果你要区分 UserId 和 string,建议给 userId 添加一个包装对象
类似这种吧,完全没有任何关系的两个类,只要结构能兼容,就可以互相赋值。这个应该是没有办法的
```
class C1 {
cc = 100
}
class C2 {
cc = 123
}
let xx:C1;
xx = new C2(); //多么希望这里报错!!!!
```
哈哈,楼主估计是从 Go 过来的. Go 里面 type 这样操作一下是两种类型了.
但是在 TypeScript 中这样不行. 这相当于 C 里面的 typedef. 不会报错的,因为没有定义一种新类型.
https://github.com/Microsoft/TypeScript/wiki/FAQ#can-i-make-a-type-alias-nominal
的回答也适合总之就是假装类型里有些不 structural compatible 的东西
coming soon...
https://github.com/microsoft/TypeScript/pull/33038