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

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

interface A {
  property: number;
}

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

interface A {
  property: Object;
}

甚至这个也可以

interface B extends A {
  property: Object;
}

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


当前回答

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

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)
}

其他回答

覆盖为别名类型

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

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中的内置类型

对于像我这样的懒人来说,简单的答案是:

type Overrided = Omit<YourInterface, 'overrideField'> & { overrideField: <type> }; 
interface Overrided extends Omit<YourInterface, 'overrideField'> {
  overrideField: <type>
}

创建修饰符类型

type Modify<T, R extends {[P in keyof T]:any} > = Omit<T, keyof R> & R;

你可以

interface ModifiedInterface extends Modify<OriginalType, {
  a: number;
  b: number;
}> {}

它会给你一个类型自动完成

不能更改现有属性的类型。

你可以添加一个属性:

interface A {
    newProperty: any;
}

而是改变现有的一种类型:

interface A {
    property: any;
}

导致一个错误:

后续变量声明必须具有相同的类型。变量 'property'必须是'number'类型,但这里有'any'类型

当然,您可以拥有自己的接口来扩展现有的接口。在这种情况下,你可以重写一个类型到一个兼容的类型,例如:

interface A {
    x: string | number;
}

interface B extends A {
    x: number;
}

顺便说一下,你可能应该避免使用Object作为类型,而是使用any类型。

在任何类型的文档中,它声明:

any类型是使用现有JavaScript的强大方式, 允许您在过程中逐渐选择加入或退出类型检查 编译。您可能希望Object扮演类似的角色 在其他语言中是这样。但是Object类型的变量只允许你 要给它们赋值-你不能调用任意的方法 他们,甚至那些真实存在的人:

let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.

试试这个:

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

用法:

type TransformedArticle = Override<Article, { id: string }>;