打字稿如何在扩展时添加嵌套类型

时间:2021-05-26 07:45:12

标签: javascript typescript interface

我有这种类型。

type Deposit {
    num1: number;
    num2: number;
}

type Nice {
   num: number;
   deposit: Deposit;
}

现在,我使用 Nice,但我需要以某种方式扩展它并且我希望它的 deposit 包含更多字段。最后是这样的:

type Deposit {
    num1: number;
    num2: number;
    num3: string;
    num4: string;
}

type Nice {
   num: number;
   deposit: Deposit;
}

但是,我无法更改 DepositNice 类型,因为它们来自库。

2 个答案:

答案 0 :(得分:2)

您可以使用 extends 关键字创建自定义子类型,并将其放在一个公共 types.ts 文件中,然后从那里导入类型,而不是直接从库中导入。

// src/types.ts

import { Deposit as DepositBase, Nice as NiceBase } from 'some-lib';

export interface Deposit extends DepositBase {
  num3: string;
  num4: string;
}

export interface Nice extends NiceBase {
  deposit: Deposit;
}

然后,使用它:

// src/some-lib-wrapper.ts

import * as someLib from 'some-lib';
import { Deposit, Nice } from './types'; // our extended types

// you can "re-type" the library functions in this wrapper module
// to use our custom extended types
export function makeDeposit(nice: Nice): Deposit {
  /* call someLib.makeDeposit here... */
}
// src/index.ts

import { makeDeposit } from './some-lib-wrapper'; // use the wrapped version
                                                  // with our extended types
import { Deposit, Nice } from './types';

// use your custom wrapped functions & types
makeDeposit(...);

答案 1 :(得分:1)

您可以使用辅助类型来扩展现有属性:

type Deposit = {
    num1: number;
    num2: number;
}

type Nice = {
    num: number;
    deposit: Deposit;
}

type ExtendProp<Obj, Prop, NewValue> = {
    [P in keyof Obj]: P extends Prop ? Obj[P] & NewValue : Obj[P]
}

type Result = ExtendProp<Nice, 'deposit', { foo: 'bar' }> // { deposit: Deposit & { foo: 'bar';  };

Playground