首页 > 解决方案 > 使用 Pick 为具有索引类型的对象构造类型

问题描述

给定以下界面:

interface Foobar {
  things?: { [key: string]: string[] };
}

PickType可以用来创建类型以供重用吗

// Manually typing it works:
// type Part { [key: string]: string[] }

// this does not:
type Part = Pick<Foobar, "things">;
const something: Part = { x: ["a", "b"] } };

Object.keys(something).forEach((thing) => {
  const needThis = something[thing];
  console.log(needThis); // <- this should return ["a", "b"]
});

使用此处的示例创建了一个代码框:https ://codesandbox.io/s/tender-edison-ejck8?file=/src/index.ts

代码编译,但有警告:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Pick<Foobar, "things">'.
  No index signature with a parameter of type 'string' was found on type 'Pick<Foobar, "things">'

标签: typescript

解决方案


Pick将使用作为第二个参数提供的键创建一个子类型。因此,在您的示例中,您将拥有这样的类型:

type Something {
 someThing: { [key: string]: string[] };
}

编辑:正如评论中提到的@mbdavis 在Pick这里似乎完全多余:

如果要使用属性类型,还应提供属性名称,如下所示:

type SomeInterface =  Foobar["someThing"]

游乐场链接


推荐阅读