Skip to content

[Suggestion] Override and identifier! for Mapped Type and extend interface #18567

Closed
@k8w

Description

@k8w

TypeScript Version: 2.4.0 / nightly (2.5.0-dev.201xxxxx)
2.5.2

Situation
There are lots of demand of more flexibility to Mapped Type. For example:

  1. Extend from a type and override some fields
  2. Turn optional field to required
  3. Only make some specific fields to optional

Suggestion

  1. Support multiple field definition in one type, the latter definition (same fields) will overwrite the previous
  2. Support identifier! for type definition which will remove null and undefined.

Code

type Full = {
  field1: string;
  field2: string;
  ....
  fieldN: string;
}

//Suggestion 1: Multiple fields in type definition and support override
type SomeOptional = {
  [P in keyof Full]: Full[P];  // extends
  [P in 'field1' | 'field2']? : Full[P];  // override field1 and field2 to optional
  xxx: string;  // and can add more fields.
}

//Suggestion 2: Identifer! to remove null and undefined
type SomeRequired = {
  [P in keyof SomeOptional]: SomeOptional[P];  // extends
  field1: SomeOptional[field1]!;  // ! will remove null and undefined from a type
}

Benifit

  1. It can resolve most problem with required and optional in current open issues. (like Add a new type Required #15012, Type to invert optionality of properties #16173, Mapped type optional -> required property issue #13224, Is this possible? Opposite of Partial Type #12578, )
  2. More flexible to extend and override, in limited complexity.

BTW, function getProperty in #12578 is a solution, but it cannot be used in declaration files.(.d.ts)

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions