扩展@types - 从接口删除字段,在接口中添加字段到字段

haz*_*111 2 typescript definitelytyped typescript-typings typescript-types

我有来自npm/@ types类型的javascript库.

我需要对@types进行两次修复,仅适用于我的应用程序,因此我无法将它们合并到DefinitelyTyped存储库中.

我需要:

  1. 从界面中删除一个字段.例:

    // before changes:
    interface A {
            a?:string;
            b?:string;
            c?:string;
    }
    
    // after changes:
    interface A {
            a?:string;
            c?:string;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在界面中的一个字段中添加更多类型.例:

    // before changes:
    interface B {
            a?: C;
    }
    
    // after changes:
    interface B {
            a?: C | D;
    }
    
    Run Code Online (Sandbox Code Playgroud)

另外,我仍然想从外部存储库下载主要的@types定义.

实现这一目标的最佳方法是什么?

Abh*_*ash 13

这可以使用以下方法解决。

import { A as AContract, B as BContract, C, D } from './contracts.ts';

// Removes 'b' property from A interface.
interface A extends Omit<AContract, 'b'> { }

interface B extends BContract {
  a?: C | D;
}
Run Code Online (Sandbox Code Playgroud)


Exp*_*lls 8

您不能在TypeScript中覆盖接口的现有属性的类型声明,但您可以通过扩展类型接口来执行此操作,因为您可以覆盖属性类型:

interface afterA extends A {
  b?: never;
}

interface afterB extends B {
  a?: C | D;
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

3363 次

最近记录:

7 年,10 月 前