首页 > 解决方案 > 打字稿动态键名

问题描述

我只想拥有一个具有动态属性的对象,例如( get , post , put )

type methodNames = "get" | "post" | "put";

interface toFetch {
    target:string,
    from: string
  }

type CommonApiQuery = Record<methodNames, toFetch[]>

我希望 CommonAPIQuery 允许对象如下所示:

const lookup : CommonApiQuery = {
  get: [{target:"students",from:"id"}]
}

但它的预期属性“post”和“put”也是。我只想在 methodNames 中至少有一个已定义的属性,但是当没有定义 methodNames 的属性时应该抛出错误。如何做到这一点?

标签: typescript

解决方案


推荐阅读