【问题标题】:Get type of an interface's property in TypeScript在 TypeScript 中获取接口属性的类型
【发布时间】:2021-07-07 22:34:53
【问题描述】:

我想通过它的属性名称从我的接口中提取一个类型,以便在记录中重用。我在按属性名称检索类型的语法上遇到困难。我正在尝试使它更具前瞻性,以便每当 id 类型更改为数字时,例如我不必找到那条记录并将其也更改为数字。

interface Account {
  name: string;
  id: string;
  createdOn: number;
}

然后在我的代码中,我设置了一个useState 类型,它是来自我的界面的id(字符串)的映射,并且是当前是否正在加载帐户的布尔值。

const [loadingAccounts, setLoadingAccounts] = useState<Record<string, boolean>>({});

我应该用什么替换string 来获得id 的类型?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以使用[]从接口中提取类型,如下所示:

    interface Account {
      name: string;
      id: string;
      createdOn: number;
    }
    
    let testVar: Account['id'];
    

    如果您将在这段代码中看到,testVar 的类型将是字符串。

    【讨论】:

    猜你喜欢
    • 2021-01-18
    • 2021-06-28
    • 2020-02-28
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    相关资源
    最近更新 更多