在另一个接口中使用Typescript接口的一个属性

3
假设我有一个如下的TypeScript接口:
export interface IMyObj {
    id: string;
    type: 'AA' | 'AZ' | 'XY';
    ...
}

现在我需要另一个接口,该接口也具有type字段。
export interface IMyOtherObj {
    ...
    type: 'AA' | 'AZ' | 'XY';
    ...
}

如您所见,我已复制了type的值。我的问题是:如何在IMyOtherObj接口中重用IMyObj.type?我尝试过以下内容:

export interface IMyOtherObj {
    ...
    type: IMyObj.type; // -> error
    ...
}

我觉得我已经接近成功了,但是还没有运气,有什么建议吗?


2
能否仅将它们作为一种类型提取出来? - undefined
5个回答

9
你的问题是TS类型系统没有.属性访问,而是使用索引类型,在你的类型定义中更改一个东西即可:
type: IMyObj['type']

如果我需要类似于X的东西,而接口具有一个属性是X[],那么提取X的类型仍然可能吗?因为这种方法将返回X[]。 - undefined

2

为您的属性type定义一个枚举,例如:

enum MyEnum {
    Aa = "AA",
    Az = "AZ",
    Xy = "XY"
}

然后像这样使用:

export interface IMyObj {
    id: string;
    type: MyEnum;
}

1
你可以创建一个仅包含类型属性定义的新接口,然后在其他接口中扩展它:
export interface ITypedObj {
    type: 'AA' | 'AZ' | 'XY';
}

export interface IMyObj extends ITypedObj {
    id: string;
}

TS手册:扩展接口


0

你有两个选择。

1. 将字段类型提取为自己的类型,并在两个地方使用它。

type ObjectType = 'AA' | 'AZ' | 'XY'
interface A {
  type: ObjectType;

}
interface B {
  type: ObjectType
}

或者如果你不能修改第一个接口,你可以让第二个接口扩展第一个的子类型。

interface A {
  type: 'AA' | 'AZ' | 'XY';

}

interface B extends Pick<A, 'type'> {

}

0
你可以使用继承功能
这样你就会有
export interface IMyObj {
    id: string;
    type: 'AA' | 'AZ' | 'XY';
    ...
}

然后

export interface IMyOtherObj extends IMyObj{
    ...
    otherthings: string;
    ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接