【发布时间】:2021-08-10 14:14:11
【问题描述】:
问题的快速总结:
我想要一个通用类型别名,在创建一些函数时为开发人员提供类型安全。它应该像这样幸运:
//Types for A and B are optional
//I left the empty object to indicate that these generic types are optional. I know that they do not work.
interface Handler<A = {}, B = {}> {
func: (input: A & B) => void;
}
//Working example with object destructuring
const foo: Handler<{bar: string}> = {
func: ({bar}) => console.log(bar)
}
//Type error
const foo: Handler<{bar: string}> = {
//rar not available
func: ({rar}) => console.log(rar)
}
这里最大的问题是这不适用于我上面使用的空对象,也不适用于Record<string, unknown> 默认值,因为两个版本都允许所有键。
我目前的解决方法如下:
type PseudoEmpty = {_:0}
interface Handler<A = PseudoEmpty, B = PseudoEmpty> {
func: (input: Omit<A & B, "_">) => void;
}
这感觉有点粗略,更像是我错过了条件类型背后的大图来自己编写正确的“空类型别名”。
此外,生成的错误消息是 Property '...' does not exist on type 'Pick '.,它没有提供很好的反馈(但是我的 IDE 自动完成功能在此设置下看起来不错)
所以以一个问题结束: 是否有一种类型可以实际评估为“无键”对象,我可以将其用于我的泛型类型默认值?
提前谢谢你
编辑:当我编辑此消息时,我的你好消息被删除了,所以请尽管这是我的帖子的结尾,但请感到欢迎!
【问题讨论】:
-
您在第二个
foo函数中有错字。你应该使用bar而不是rar -
另外,我不明白为什么它不适用于空对象?能否提供更多示例?
-
好的,我确实在上面提供的示例中使用了空对象。我使用的泛型类型系统可能存在其他问题(实际设置比这更复杂)。无论如何感谢您的帮助!
标签: typescript generics types interface intersection