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

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

interface A {
  property: number;
}

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

interface A {
  property: Object;
}

甚至这个也可以

interface B extends A {
  property: Object;
}

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


当前回答

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

从类型中排除属性

interface A {
    x: string
}

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

的接口:

interface A {
    x: string
}

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

其他回答

有趣的是,我花了一天的时间调查解决同一个案子的可能性。 我发现这样做是不可能的:

// a.ts - module
export interface A {
    x: string | any;
}

// b.ts - module
import {A} from './a';

type SomeOtherType = {
  coolStuff: number
}

interface B extends A {
    x: SomeOtherType;
}

产生原因模块可能不知道应用程序中所有可用的类型。从各个地方移植所有东西,编写这样的代码是很无聊的。

export interface A {
    x: A | B | C | D ... Million Types Later
}

您必须稍后定义类型,以使自动完成工作良好。


所以你可以欺骗一下:

// a.ts - module
export interface A {
    x: string;
}

默认保留some类型,当不需要重写时,允许自动完成工作。

Then

// b.ts - module
import {A} from './a';

type SomeOtherType = {
  coolStuff: number
}

// @ts-ignore
interface B extends A {
    x: SomeOtherType;
}

在这里使用@ts-ignore标志禁用愚蠢的异常,告诉我们我们做错了什么。有趣的是,一切都按照预期进行。

在我的情况下,我减少了类型x的范围,它允许我做更严格的代码。例如,你有一个100个属性的列表,你把它减少到10个,以避免愚蠢的情况

创建修饰符类型

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

你可以

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

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

日期: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" }

对于缩小属性的类型,简单的扩展是完美的,正如Nitzan的回答:

interface A {
    x: string | number;
}

interface B extends A {
    x: number;
}

为了扩大,或通常覆盖类型,你可以做Zskycat的解决方案:

interface A {
    x: string
}

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

但是,如果您的接口A扩展了一个通用接口,那么在使用省略时,您将失去A的剩余属性的自定义类型。

e.g.

interface A extends Record<string | number, number | string | boolean> {
    x: string;
    y: boolean;
}

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

let b: B = { x: 2, y: "hi" }; // no error on b.y! 

原因是,在内部,省略只在排除<keyof A, 'x'>键,这将是一般字符串|数字在我们的情况下。因此,B将变成{x: number;}并接受数字| string | boolean类型的任何额外属性。


为了解决这个问题,我提出了一个不同的OverrideProps实用程序类型如下:

type OverrideProps<M, N> = { [P in keyof M]: P extends keyof N ? N[P] : M[P] };

例子:

type OverrideProps<M, N> = { [P in keyof M]: P extends keyof N ? N[P] : M[P] };

interface A extends Record<string | number, number | string | boolean> {
    x: string;
    y: boolean;
}

export type B = OverrideProps<A, { x: number }>;

let b: B = { x: 2, y: "hi" }; // error: b.y should be 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
}