Skip to content

Generic constrained to mapped type should work with spread types #16780

@sccolbert

Description

@sccolbert

I think I'm getting a false error related to object spread types. Example code below. The shape of Record is limited to simple vanilla objects with no nested/methods/etc.

TypeScript Version: 2.3.2

Code

namespace Foo {

    type Value = string | number | boolean | null;

    type Record<K extends string> = { readonly [P in K]: Value; };

    type RecordTable<T extends Record<keyof T>> = { readonly [id: string]: T; }

    function update<T extends Record<keyof T>>(table: RecordTable<T>, id: string, values: Partial<T>): RecordTable<T> {

      let record = { ...table[id], ...values };  // This line fails at `...table[id]`` with "error TS2698: Spread types may only be created from object types."

      return { ...table, [id]: record };
    }

    // Usage
    interface IFoo extends Record<keyof IFoo> {
      foo: number;
      bar: string;
      //baz: number[];  // fails like it should when uncommented
    }

    let table: RecordTable<IFoo>;

    update(table, 'someId', { foo: 12 });  // okay
    update(table, 'someId', { baz: 4 });   // fails like it should, "baz" invalid property
}

Expected behavior:
Should compile cleanly.

Actual behavior:
Does not compile.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptDuplicateAn existing issue was already created

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions