我有一个问题,我试图在TypeScript中为共享模块创建一个接口,为了这个问题的目的让我们假设具有以下形状:
interface A {
x: string;
y: { [name: string]: (...args: any) => {type: string; payload?: any} };
z?: () => any
}
这个界面的目的有两个:
例如,如果我有:
const bar = {
x: 'hello',
y: { 'world': (a: string, b: number) => ({ type: a, payload: b}) }
}
注意缺少对接口A
的引用。
如果我那么输入:bar.
我会得到intellisense它有属性x
和y
。更多的是,在输入bar.y.
时,我会得到提示world
存在以及与之关联的函数类型。
但是,如果我添加A
:
const bar: A = {
x: 'hello',
y: { 'world': (a: string, b: number) => ({ type: a, payload: b}) }
}
它有助于某人意外添加错误的属性,如:
const bar: A = {
iDontBelong: true, // wrong
x: 'hello',
y: { 'world': (a: string, b: number) => ({ type: a, payload: b}) }
}
甚至
const bar: A = {
x: 5, // wrong
y: { 'world': (a: string, b: number) => ({ type: a, payload: b}) }
}
现在的问题是,如果有人要导入bar
并输入bar.
,他们会得到直接用于接口A
的建议。它失去了bar
只有x
和y
(并且没有z
)的知识,它也失去了关于y
特定类型的信息,这意味着它甚至不知道world
存在于y
。
有没有办法让这两件事同时存在?
有没有办法让这两件事同时存在
一旦你说: A
然后你将不会得到intellisense对象袋([name: string]
)。
您可以通过不注释但进行类型测试来避免这种情况,例如:
const bar = {
x: 'hello',
y: { 'world': (a: string, b: number) => ({ type: a, payload: b}) }
}
const _ensureA: A = bar; // Type test