我是否可以基于同级键动态键入对象文字的键?

时间:2019-08-15 22:57:11

标签: typescript

我想根据其他字段的类型来输入带有某些字段的复杂对象。以下几乎真实的代码是否可行?

interface CafeSpec {
  menu: { [key: string]: number }; // Suppose we could call this type Items
  special_disposal: { [K in keyof Partial<Items>]: string } 
}

let bridgeLocation: CafeSpec = {
  menu: {
    cake: 5,
    toast: 20
  },
  special_disposal: {
    cake: "eat",
    flowers: "take home"  // This should error! flowers not key of Items
  }
}

我对任何需要多次写出菜单项的解决方案都不感兴趣,因此明确声明通用菜单的类型是不可能的。

到目前为止,我最好的解决方案是使用函数。但是,这仍然比我想要的更为冗长。

interface Menu {
    [key: string]: number;
}

interface CafeSpec<M extends Menu> {
    menu: M;
    special_disposal: { [K in keyof Partial<M>]: string};
}

type PartialSpec<M extends Menu> = Omit<CafeSpec<M>, "menu">

function createCafe<M extends Menu>(menu: M, extra: PartialSpec<M>): CafeSpec<M> {
    return {...extra, menu};
}

let newLocation = createCafe(
  {
    cake: 5,
    toast: 20
  },
  {
    special_disposal: 
    {
        cake: "eat",
        flowers: "take home" // Nice error here shown below
    }
  }
);
Object literal may only specify known properties,
 and 'flowers' does not exist in type 
 '{ cake?: string | undefined; toast?: string | undefined; }'

0 个答案:

没有答案