是否有方法更改*.d中定义的接口属性的类型?Ts在typescript中?

例如: x.d.ts中的接口定义为

interface A {
  property: number;
}

我想在我写入的typescript文件中改变它

interface A {
  property: Object;
}

甚至这个也可以

interface B extends A {
  property: Object;
}

这种方法有效吗?当我试我的系统时,它不工作。只是想确认一下有没有可能?


当前回答

扩展接口时省略该属性:

interface A {
  a: number;
  b: number;
}

interface B extends Omit<A, 'a'> {
  a: boolean;
}

其他回答

我使用一种方法,首先过滤字段,然后组合它们。

从类型中排除属性

interface A {
    x: string
}

export type B = Omit<A, 'x'> & { x: number };

的接口:

interface A {
    x: string
}

interface B extends Omit<A, 'x'> {
  x: number
}

注意:不确定我在这个答案中使用的语法是否可用,当写旧的答案时,但我认为这是解决这个问题中提到的例子的更好方法。


我有一些与这个主题相关的问题(覆盖接口属性),这是我如何处理它:

首先创建一个泛型接口,其中包含您想要使用的可能类型。

您甚至可以为通用参数使用选择默认值,如<T extends number | SOME_OBJECT = number>中所示

type SOME_OBJECT = { foo: "bar" }

interface INTERFACE_A <T extends number | SOME_OBJECT = number> {
  property: T;
}

然后你可以根据该契约创建新类型,通过将一个值传递给泛型参数(或省略它并使用默认值):

type A_NUMBER = INTERFACE_A;                   // USES THE default = number TYPE. SAME AS INTERFACE_A<number>
type A_SOME_OBJECT = INTERFACE_A<SOME_OBJECT>  // MAKES { property: SOME_OBJECT }

这就是结果:

const aNumber: A_NUMBER = {
    property: 111  // THIS EXPECTS A NUMBER
}

const anObject: A_SOME_OBJECT = {
    property: {   // THIS EXPECTS SOME_OBJECT
        foo: "bar"
    }
}

打印稿操场

更好的解决方案是使用以下修改类型(双关语)的这个答案

export type Modify<T, R extends Partial<T>> = Omit<T, keyof R> & R;

这也将检查你覆盖的键是否也存在于原始接口中,从而确保如果原始接口更改了名称,那么你将得到编译时错误,你也必须更改名称。

解释:

举个例子。

interface OriginalInterface {
    id: string
}

修改后的型号如下图所示

interface ModifiedInterface {
    id: number
}

现在,假设在未来,OriginalInterface的id被重命名为uId,然后使用我的类型实用程序,你将得到如下错误

interface ModifiedInterface {
    id: number // Type '{ geo_point1: GeoPoint | null; }' has no properties in common with type 'Partial<Address>'.ts(2559)
}

覆盖接口的两个或多个属性的解决方案:

接口原始{ 答:字符串; b:字符串; c:字符串; } interface Modified extends省略<Original, 'a' | 'b'> { 一个吗?:字符串;//设置为可选 b:布尔;//设置为布尔值 d:数量;//添加另一个属性 }

来自TypeScript文档

如果你只想修改一个现有属性的类型,而不是删除它,那么&就足够了:

// Style that accepts both number and percent(string)
type BoxStyle = {
  height?: string | number,
  width?: string | number,
  padding?: string | number,
  borderRadius?: string | number,
}

// These are both valid
const box1: BoxStyle = {height: '20%', width: '20%', padding: 0, borderRadius: 5}
const box2: BoxStyle = {height: 85, width: 85, padding: 0, borderRadius: 5}

// Override height and width to be only numbers
type BoxStyleNumeric = BoxStyle & {
  height?: number,
  width?: number,
}

// This is still valid
const box3: BoxStyleNumeric = {height: 85, width: 85, padding: 0, borderRadius: 5}

// This is not valid anymore
const box4: BoxStyleNumeric = {height: '20%', width: '20%', padding: 0, borderRadius: 5}