【发布时间】:2021-05-01 19:02:55
【问题描述】:
我有一个像这样的常量对象:
const shortcuts = {
save: {
label: 'ctrl+s',
action: (documentId: string) => saveDocument(documentId)
},
open: {
label: 'ctrl+o',
action: (name: string, type: string) => loadDocument(documentName, extension),
thisShouldError: 'thisShouldError' // not allowed property
},
// etc...
} as const
我想确保所有快捷方式都遵循如下所示的所需形状,并且没有添加多余的属性。
interface DesiredShape {
label: string,
action: (...args: any[]) => void
}
特别是,我希望shortcuts 的上述定义出错,因为不允许使用open.thisShouldError。同时,我不想丢失任何类型信息,即当我做shortcuts.save.action时,我想得到函数的实际类型签名为(documentId: string) => saveDocument(documentId),而不仅仅是通用的(...args: any[]) => void。
有可能实现吗?
到目前为止我所做的尝试:
我可以使用object literals limitations 来执行此操作,但是我会丢失类型信息。
我还尝试确保键的区别如下never,但似乎 TS 只将无处不在的键带入ActualKeys。
type ActualKeys = keyof typeof shortcuts['save' | 'open']
type PermittedKeys = keyof DesiredShape
// does not work because ActualKeys does not include `thisShouldError`
assertNever(null as unknown as Exclude<ActualKeys,PermittedKeys>)
【问题讨论】:
标签: typescript types