> Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
这种情况下的解决方法就是断言2次,先转化为any/unknown, 再断言为其他类型
1
const a = (expr as any) as T;
Type 和 Interface的区别
Type 创建后不可二次修改, Interface 始终可扩展编辑的
联合类型使用
type U= A|B
如果使用的是A 跟B都有的属性,那么ts不会报错, 如果使用的是A或者 B 独有的属性,那么使用前需要先判断具体是哪一个类型,ts才不会报错。
1 2 3 4 5 6 7 8 9
function printId(id: number | string) { if (typeof id === "string") { // In this branch, id is of type 'string' console.log(id.toUpperCase()); } else { // Here, id is of type 'number' console.log(id); } }