microsoft / microsoft/TypeScript

Optional fields affecting keyof operator in generic class decorators

Open
#29,222 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Domain: Mapped Types In Discussion Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.2.2

Search Terms:
class decorator keyof typescript

Code

function View<T>(name: string, fields: (keyof T)[]) {
  return (target: new(...args: any[]) => T) => {
    // Do something with fields
  };
}

// works
@View('active', ['street1', 'street2'])
class Address {
  street1: string;
  street2: string;
}

// broken
@View('active', ['street1', 'street2'])
class AddressBroken {
  street1: string;
  street2?: string;
}

Expected behavior:
Both scenarios should work above.

Actual behavior:
It appears that optional fields are causing the decorator to create invalid types.

Argument of type 'typeof AddressBroken' is not assignable to parameter of type 'new (...args: any[]) => { street1: any; street2: any; }'.
  Type 'AddressBroken' is not assignable to type '{ street1: any; street2: any; }'.
    Property 'street2' is optional in type 'AddressBroken' but required in type '{ street1: any; street2: any; }'.
1234

Playground Link:
Playground Sample

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked Playground sample and reproduce the decorator error involving keyof, generic classes, and an optional field. Trace the compiler's handling of the decorator target type, then add a regression test covering both Address and AddressBroken and verify that both examples compile without the reported error.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.