2

Consider the following interface in TypeScript's lib.d.ts:

interface HTMLElement extends Element {
    accessKey: string;
    readonly children: HTMLCollection;
    contentEditable: string;
    readonly dataset: DOMStringMap;
    dir: string;
    draggable: boolean;
    // ... many more
}

How would I pick only the properties out of this interface that are not readonly, without having to manually identify and input them all (as illustrated below)?

type WriteableHTMLElProps = Pick<HTMLElement, "accessKey"|"contentEditable" /* ... */>

Note: a proper solution should also handle the non-readonly properties of the interfaces that this one extends.

Jamie Birch
  • 5,839
  • 1
  • 46
  • 60
  • I hadn't found this issue when I created mine. But look! There is a proposed solution now at https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir – DanielM Dec 06 '18 at 19:55
  • @DanielM those are some seriously arcane types – there's a few constructions I don't even recognise in his solution, and I've been no slouch on keeping up with TypeScript updates. Thanks for pointing me to this! – Jamie Birch Dec 06 '18 at 23:05

1 Answers1

5

I can't think of a mechanism that would allow you to do this automatically in the current version of TypeScript.

You would need the proposed ideas for mapped type filtering to be available in order to do this (assuming that readonly would be filterable in the final implementation.

For example (the syntax is under discussion in a few places depending on the exact details):

type OnlyReadonlyMembers<T> = {
    [P in keyof T where T[P] is readonly]: T[P];
}
Fenton
  • 241,084
  • 71
  • 387
  • 401