是否可以创建一个表示typeguard的类型,例如,如果您希望有一个类型来强制创建一个对象,其中键表示预期的true
类型guard断言解析的typeof
返回值,如下所示:
type ValueMap = {
string: string;
number: number;
};
type Value = ValueMap[keyof ValueMap];
您的值可以是字符串或数字.
可以创建这样的类型来判断值:
type Guards = { [K in keyof ValueMap]: (value: Value) => boolean };
但这些函数没有作为类型保护输入,我想要这样的内容:
type TypedGuards = { [K in keyof ValueMap]: (value: Value):value is K => boolean };
但这是无效的语法.
我希望该类型可以使用,以便
const guards: Guards = {
number: (value) => true,
string: (value) => true,
};
在一些条件陈述(例如if(guard(value)){...}
)中推断出正确的类型
所以基本上希望与
const typeGuards = {
number: (value: Value): value is number => true,
string: (value: Value): value is string => true,
};
但我想创建一个类型来表示这一点.
如果我做
const typeGuards = {
number: (value: Value): value is number => true,
string: (value: Value): value is string => true,
};
type TypeGuards = typeof typeGuards
我确实得到
type TypeGuards = {
number: (value: Value) => value is number;
string: (value: Value) => value is string;
}
但我想将其明确地表达为一个类型.
谢谢