【发布时间】:2020-09-29 20:56:19
【问题描述】:
所以最初是为了强制执行约束,我只是应用这样的接口
// this is the constraint
interface Topic {
[key: string]: (...args: any[]) => Promise<any>
}
// object that must pass the constraint
const topic: Topic = {
// GOOD: topic methods must conform
async actuate(a: boolean) {}
}
// BAD: type signature broken
topic.actuate(true)
但问题是 topic 的类型减少到最低公分母,这是约束 Topic — 相反,我希望 topic 保留其详细的类型签名,用于像 @987654325 这样的方法@
所以我发现这种蹩脚的 hacky 方法可以两全其美:
interface Topic {
[key: string]: (...args: any[]) => Promise<any>
}
type TopicConstraint<T extends Topic> = T
const topic = {
// GOOD: topic methods must conform
async actuate(a: boolean) {}
}
// BAD: weird ugly unused type variable constraint hack
// BAD: all topic constraint errors actually land here
type TopicCheck = TopicConstraint<typeof topic>
// GOOD: type signature preserved
topic.actuate(true)
有没有更合适的方法来更优雅地完成同样的事情?我不知道如何在 typescript 中表达这种约束情况
但我还是忍不住觉得有什么特别的地方
type TopicConstraint<T extends Topic> = T
这可能是关键......这让我想做非法的打字稿之类的事情
// invalid, but i need something in the same spirit
const topic = TopicConstraint<{
async actuate(a: boolean) {}
}>
// invalid, but i need something in the same spirit
const topic: TopicConstraint<@self> = {
async actuate(a: boolean) {}
}
我正在寻找一种我找不到的语法。有没有不同的方法?谢谢!
【问题讨论】:
标签: typescript