在TypeScript中是否有一种方法可以使用接口作为保护而不会丢失对象的特异性?

问题描述 投票:1回答:1

我有一个问题,我试图在TypeScript中为共享模块创建一个接口,为了这个问题的目的让我们假设具有以下形状:

interface A {
  x: string;
  y: { [name: string]: (...args: any) => {type: string; payload?: any} };
  z?: () => any
}

这个界面的目的有两个:

  1. 对于制作模块的人,我希望他们能够知道他们创建的东西符合A.
  2. 对于使用该模块的人,我希望他们能够进行最具体的打字。

例如,如果我有:

const bar = {
  x: 'hello',
  y: { 'world': (a: string, b: number) => ({ type: a, payload: b}) }
}

注意缺少对接口A的引用。

如果我那么输入:bar.我会得到intellisense它有属性xy。更多的是,在输入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只有xy(并且没有z)的知识,它也失去了关于y特定类型的信息,这意味着它甚至不知道world存在于y

有没有办法让这两件事同时存在?

typescript types interface
1个回答
1
投票

有没有办法让这两件事同时存在

一旦你说: A然后你将不会得到intellisense对象袋([name: string])。

您可以通过不注释但进行类型测试来避免这种情况,例如:

const bar = {
  x: 'hello',
  y: { 'world': (a: string, b: number) => ({ type: a, payload: b}) }
}
const _ensureA: A = bar; // Type test 
© www.soinside.com 2019 - 2024. All rights reserved.