我读过关于详尽的类型检查的文章,这确实是打字稿的一个很好的特点。我用它做了实验,发现了一些奇怪的行为(或者没有被打字组完全实现)。这是我现在的代码(非常好用):
type factType = 'test-1' | 'test-2'
function doSomething(fact: factType) {
if (fact ==='test-1') {
return true;
} else if(fact === 'test-2') {
return true;
}
assertUnreachable(fact);
}
function assertUnreachable(x: never): never {
throw new Error("Didn't expect to get here");
}但是,当我使用一个函数作为分支条件时,它就会中断。它说“'string‘类型的参数不能分配给’从不‘事实的参数:”test-2“:
type factType = 'test-1' | 'test-2';
function doSomething(fact: factType) {
if (fact === 'test-1') {
return true;
} else if (isTest2(fact)) {
return true;
}
assertUnreachable(fact);
}
function isTest2(fact: factType) {
return fact === 'test-2';
}我试过使用fact as 'test-2',但它不起作用。有人知道如何解决这个问题吗?或者原因可能是什么?我认为这是打字稿,但我绝不是一个专家!
谢谢!
发布于 2021-10-04 09:37:27
使用类型谓词向TS表示函数检查fact是否为test-2类型。
function isTest2(fact: factType): fact is 'test-2' {
return fact === 'test-2';
}https://stackoverflow.com/questions/69433784
复制相似问题