Description
Suggestion
π Search Terms
fieldof , mapped type, mapped private protected
Can maybe related: #35416 #4822
β Viability Checklist
My suggestion meets these guidelines:
- β This wouldn't be a breaking change in existing TypeScript/JavaScript code
- β This wouldn't change the runtime behavior of existing JavaScript code
- β This could be implemented without emitting different JS based on the types of the expressions
- [ ?] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- [ ?] This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
add a new utility fieldof
for map easily all keys field include, private and protected
π Motivating Example
i have similar issue here where some pattern make complications !
type Writable<T> = { -readonly [P in keyof T]: T[P] }; // make writable A.parent for Childrable
class A {
public readonly parent?: A
protected Renderer() { };
}
// in this context, let say is a component added to A (plugin), with some method authorized to write on A.
class Childrable {
public entity!: A;
public readonly children: A[] = [];
public addChild(...children: Writable<A>[]) {
if (children.length > 1) {
for (const child of children) this.addChild(child);
} else {
const child = children[0];
if (child) {
// So Writable<A> allow replace A.parent
child.parent = this.entity;
// But Writable<A> seem remove protected.Renderer prototype and now they are not compatible
// I need allow replace A.parent and add A in Childrable.children in the same scope !
this.children.push(child);
}
}
return this;
}
}
It would be great to see a easy way to handle more patterns with protected
, private
fields when we map types for specific case.
In my upper example, Childrable
is a component where you can attach to Entity A
, and Childrable
have some method where allowed to write in some readOnly field
from A.
But map to readOnly will remove private and protected field and will create issue, in this case fieldof
will fix the issue, becaue we want allow Writable, in context of component have method for mutate entities.
π» Use Cases
type Writable<T> = { -readonly [P in fieldof T]: T[P] };
So same as keyof
, but include all private
and protected
fields for specific pattern.
This will also maybe unlock more powerful features and patterns, but let just talk about this specific case for now.