【问题标题】:Adding properties to an existing type in a different files with TypeScript使用 TypeScript 将属性添加到不同文件中的现有类型
【发布时间】:2020-12-09 04:54:53
【问题描述】:

我有一个包含typeinterface 变量的文件(所有这些变量都是导出的),我需要从不同的文件中为这个变量添加新属性,而不需要扩展。我的意思是从不同的文件中更改同一个变量。

示例: 文件a:

export interface ButtonPresentationProps {
    buttonType?: "outline" | "solid";
    variant?: ButtonVariants;
}

我需要从file b 向接口添加新属性,而无需创建新的接口变量,因为我在不同的地方使用该接口。

怎么做?

【问题讨论】:

  • 您正在寻找声明合并。

标签: javascript reactjs typescript ecmascript-6


【解决方案1】:

使用声明 -

对于已经扩展的 -

import { ButtonPresentationProps } from "./myfile";

...你会使用 -

declare "./myfile" {
    export interface ButtonPresentationProps {
        buttonType?: "outline" | "solid";
        variant?: ButtonVariants;
    }
}

只要它位于编译链中的某个位置,它就会被使用,因此粘贴在 *.d.ts 文件中并直接导入通常很有用 - 但可以随意粘贴在使用它的同一个文件中。

【讨论】:

  • 请注意,这将适用于任何输入文件 - 甚至库等 - 所以这是修复不正确的事情等的好方法 :-)
  • 我创建了 2 个文件 A 和 B A File: interface MyInterface { name: string; } 导出默认 MyInterface; B 文件:从 './A' 导入 MyInterface;声明模块'./A' { interface MyInterface { age: number; } } 并在 Main.ts const test: MyInterface = { name: "Test", age: 5, } 但它返回错误 "Type '{ name: string; age: number; }' is notassignable to type 'MyInterface '. 对象字面量只能指定已知属性,而 'age' 不存在于类型 'MyInterface' 中。”
  • 你可以在这里看到我的代码stackoverflow.com/a/63495732/14133817
  • 我的错 - 忘记在第二个添加 export。顺便说一句,如果你能帮上忙,你不应该使用export default - 它带来的问题远远多于解决的问题 - basarat.gitbook.io/typescript/main-1/defaultisbad
猜你喜欢
  • 1970-01-01
  • 2013-08-27
  • 2018-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
相关资源
最近更新 更多