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

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

interface A {
  property: number;
}

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

interface A {
  property: Object;
}

甚至这个也可以

interface B extends A {
  property: Object;
}

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


当前回答

如果其他人需要一个通用的实用程序类型来做到这一点,我提出了以下解决方案:

/**
 * Returns object T, but with T[K] overridden to type U.
 * @example
 * type MyObject = { a: number, b: string }
 * OverrideProperty<MyObject, "a", string> // returns { a: string, b: string }
 */
export type OverrideProperty<T, K extends keyof T, U> = Omit<T, K> & { [P in keyof Pick<T, K>]: U };

我需要这个,因为在我的例子中,覆盖的关键是一个泛型本身。

如果没有准备好省略,请参阅从类型中排除属性。

其他回答

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

从类型中排除属性

interface A {
    x: string
}

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

的接口:

interface A {
    x: string
}

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

如果其他人需要一个通用的实用程序类型来做到这一点,我提出了以下解决方案:

/**
 * Returns object T, but with T[K] overridden to type U.
 * @example
 * type MyObject = { a: number, b: string }
 * OverrideProperty<MyObject, "a", string> // returns { a: string, b: string }
 */
export type OverrideProperty<T, K extends keyof T, U> = Omit<T, K> & { [P in keyof Pick<T, K>]: U };

我需要这个,因为在我的例子中,覆盖的关键是一个泛型本身。

如果没有准备好省略,请参阅从类型中排除属性。

覆盖为别名类型

你可以使用这个类型的别名:

type Override<T, K extends { [P in keyof T]: any } | string> =
  K extends string
    ? Omit<T, K>
    : Omit<T, keyof K> & K;

在下面的语法中使用alike:

全球接口

interface IFirst {
    username: string;
}

接口由重写只是名称

interface ISecond extends Override<IFirst, 'username'> {
    username: number;
}

类型别名覆盖

type IThird = Override<IFirst, { username: boolean }>;

编辑:

我试图通过将问题作为建议发送到typescript Repo,将这个别名类型添加为typescript中的内置类型

日期:19/3/2021。 我认为最新的typescript(4.1.2)版本支持d.ts文件中的接口覆盖。

// in test.d.ts

interface A {
  a: string
}

export interface B extends A {
  a: number
}

// in any ts file
import { B } from 'test.d.ts'

// this will work
const test: B = { a: 3 }

// this will not work
const test1: B = { a: "3" }

扩展接口时省略该属性:

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

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