TypeScript 实用程序类型:对象条目元组

ktca8awb  于 9个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(110)

搜索词

实用类型,对象条目,元组,Map类型

建议

一个 Entries<T> 实用类型,用于构造 lib.es5.d.ts 中所有类型为 T 的对象条目元组的并集。

  1. /**
  2. * Construct a union of all object entry tuples of type T
  3. */
  4. type Entries<T> = {
  5. [P in keyof T]: [P, T[P]];
  6. }[keyof T];

用例

我理解为什么 Object.entries 提供 string 作为键类型而不是实际键(因为可能存在比这些在类型中定义的更多的实际键)。我参考了这里的讨论。
然而,有时候我们可以确信只有类型中定义的属性会在运行时出现,并且发现这样的实用类型可以帮助更严格地定义这类类型,尤其是在测试中。

示例

  1. const expected = {
  2. foo: "foo",
  3. bar: "Bar",
  4. baz: "BAZ",
  5. } as const;
  6. (Object.entries(expected) as Entries<typeof expected>).forEach(([input, output]) => {
  7. // where `myFunction`'s first parameter only accepts `"foo" | "bar" | "baz"` (or a superset)
  8. expect(myFunction(input)).to.equal(output);
  9. });
  1. function thatAcceptsJsxAttributeTuples(attributes: readonly Entries<JSX.IntrinsicElements["path"][]>): void {
  2. // ...
  3. }

检查清单

我的建议满足以下准则:

  • 这不会对现有的 TypeScript/JavaScript 代码造成破坏性改变
  • 这不会改变现有 JavaScript 代码的运行时行为
  • 这可以在不根据表达式的类型发出不同的 JS 的情况下实现
  • 这不是一个运行时特性(例如库功能、JavaScript 输出的非 ECMAScript 语法等)
  • 这个特性将与 TypeScript's Design Goals 的其他部分保持一致。
sc4hvdpw

sc4hvdpw1#

我正准备将这个报告为一个bug。我将留下我编写的演示,提炼自我个人的使用案例:

  1. type O = { [key: string]: unknown };
  2. type B<A extends O> = { [K in keyof A]: A[K] };
  3. class Test<A extends O> {
  4. public constructor(private a: A) {}
  5. public test() {
  6. const b = {} as B<A>;
  7. for (const [key, value] of Object.entries(this.a)) {
  8. b[key] = value; // error: Type 'string' cannot be used to index type 'B<A>'.
  9. b[key as keyof A] = value as A[keyof A];
  10. }
  11. return b;
  12. }
  13. }

相关问题