【问题标题】:Extract Interface from Existing Literal从现有文字中提取接口
【发布时间】:2017-12-04 20:02:48
【问题描述】:

假设我有一个如下的对象字面量:

const defaultSettings = {
  height: 100,
  width: 100,
  color: 'red'
}

有没有什么方法可以轻松获得该对象的接口,而不必手动声明这样的接口?

interface Settings {
  height: number,
  width: number,
  color: string
}

【问题讨论】:

  • 你打算用那个界面做什么?
  • 如果type Settings = typeof defaultSettings;对你不起作用,你可以尝试使用来自this answer的脚本

标签: typescript


【解决方案1】:

在较新版本的 TypeScript 中,您可以使用接口扩展类型别名。因此,您可以通过执行以下操作来获得接口:

const defaultSettings = {
    height: 100,
    width: 100,
    color: 'red'
};

type SettingsTypeAlias = typeof defaultSettings;

interface Settings extends SettingsTypeAlias {
}

但我认为没有必要。你不妨这样做:

type Settings = typeof defaultSettings;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    相关资源
    最近更新 更多