如何从界面中仅选择非只读字段?

Jam*_*rch 2 typescript

考虑 TypeScript 中的以下接口lib.d.ts

interface HTMLElement extends Element {
    accessKey: string;
    readonly children: HTMLCollection;
    contentEditable: string;
    readonly dataset: DOMStringMap;
    dir: string;
    draggable: boolean;
    // ... many more
}
Run Code Online (Sandbox Code Playgroud)

我如何仅从该界面中选择不属于 的属性readonly,而无需手动识别和输入所有属性(如下所示)?

type WriteableHTMLElProps = Pick<HTMLElement, "accessKey"|"contentEditable" /* ... */>
Run Code Online (Sandbox Code Playgroud)

注意:正确的解决方案readonly应该处理该扩展的接口的非属性。

Fen*_*ton 5

我想不出一种机制可以让您在当前版本的 TypeScript 中自动执行此操作。

为了做到这一点,您需要提供映射类型过滤的建议想法(假设只读在最终实现中是可过滤的)。

例如(语法正在一些地方讨论,具体取决于具体细节):

type OnlyReadonlyMembers<T> = {
    [P in keyof T where T[P] is readonly]: T[P];
}
Run Code Online (Sandbox Code Playgroud)