类型 'string' 的参数不能分配给字符串常量并集类型的参数



我再次在这里寻求一些关于Typescript启发式的指导。我在写类型保护时遇到了麻烦,因为Typescript在比较时想要太窄。

考虑以下场景(或Typescript Playground):

const FOO = 'foo' as const;
const BAR = 'bar' as const;
const ALL_THINGS = [FOO, BAR];
type AllThingsType = typeof ALL_THINGS[number];
function isAllThings(value: unknown): value is AllThingsType {
return typeof value === 'string' && ALL_THINGS.includes(value);
}

错误如下:

Argument of type 'string' is not assignable to parameter of type '"foo" | "bar"'.ts(2345)

技术上有一种方法可以解决这个问题:

function isAllThingsWorkaround(value: unknown): value is AllThingsType {
return typeof value === 'string' && (ALL_THINGS as string[]).includes(value);
}

我是否错过了一些关于我应该如何做到这一点的东西?我分享的代码片段是一个简化版本,您可以假设ALL_THINGS实际上是一个包含近25个const的集合。我该如何改进这一点以避免变通?

谢谢你的帮助!

您可以这样做的一种方法是不使用.includes

const FOO = 'foo' as const;
const BAR = 'bar' as const;
const ALL_THINGS = [FOO, BAR];
type AllThingsType = typeof ALL_THINGS[number];
function isAllThings(value: unknown): value is AllThingsType {
return typeof value === 'string' && ALL_THINGS.some(a => a === value);
}
console.log(isAllThings("cat")); // false
console.log(isAllThings("foo")); // true

这种方式不需要类型转换,您可以决定"包括"实际上是指,不要让javascript决定。

最新更新