[Feature Request] fieldof similar to keyof but include private and protected field
Suggestion
🔍 Search Terms
fieldof , mapped type, mapped private protected Can maybe related: https://github.com/microsoft/TypeScript/issues/35416 https://github.com/microsoft/TypeScript/issues/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<A>, 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.
The only cases I could imagine this being potentially useful are to allow Required<X> and Writable<X> to be assignable to X for any class X with protected fields. In any other case this would break the most basic use case of protected methods since protected fields are checked for collision between classes not assignability.
As for your case you declare A.parent to be readonly which means it shouldn't be assigned outside the constructor and you are asking for a feature to literally allow you to break that assurance, so I'm not convinced even for the Writable case it is a good idea.
I'm pretty sure you just want the argument to be A not Writable<A> so that it is expected for external users to pass actual instances and then use a type assert inside the method to allow you to modify the property despite that not being allowed according to the declaration of A. playground
class Childrable {
public entity!: A;
public readonly children: A[] = [];
public addChild(...children: A[]) {
// ...
const child = children[0];
if (child) {
// use type assertion here to indicate we are breaking the declared type in A
(child as Writable<A>).parent = this.entity;
this.children.push(child);
}
return this;
}
}
I found a way by abstract class with a method useWritable()
But it would still be interesting to be able to extract all the fields.
Am not fan of type assertion expression for readability.
export abstract class Token extends Entity {
public readonly parent?: Token;
isContainer(): this is Container {
return false;
}
isPrimitive(): this is Primitive {
return false;
}
useWritable(): Writable<this> {
return this;
}
}
export class Container extends Token {
declare public readonly parent?: Container;
public readonly children: Token[] = [];
public override isContainer(){
return true;
}
protected override get Renderer() {
return Renderer;
}
public addChild( ...children: Token[] ) {
if ( children.length > 1 ) {
for ( const child of children ) this.addChild( child );
} else {
const child = children[0];
if ( child ) {
if ( child.parent?.isContainer() ) child.parent.removeChild( child );
child.useWritable().parent = this;
this.children.push( child );
}
}
return this;
}
}
I have a use case for this wherein I'm using branded types to create a branded class (similar to what https://www.npmjs.com/package/@prosopo/ts-brand does) and the class that I am branding contains a private field.
class Foo {
#privateField: string
}
const BrandedFoo = brandedClass(Foo, 'brand')
const instance = new BrandedFoo()
So the instance I create is actually a Foo (and should have the private member) but it is not assignable to Foo because the type mapping that creates the branded class uses keyof:
export type Resolve<T> = T extends Function ? T : { [K in keyof T]: T[K] };
export const brandKey = Symbol("brand");
export type Brand<T, U> = Resolve<
T & {
[brandKey]: U;
}
>;
EDIT: So as not to waste your time, I want you to know that I'm not currently blocked on this. I ended up removing that Resolve type and T & { [brandKey]: U } works just fine with private members.
I don't really see the point in handling Function in branding anyway.
Just want to add, there is another use-case for this that relates to testing as it would allow us to use the spyOn-like features of some test frameworks.
I've described this here: https://github.com/microsoft/TypeScript/issues/61595
Rough example:
// Define a utility type to make all members of a class public using the 'indexof'/'fieldof' operator.
type MakePublic<T> = { [K in indexof T]: T[K] };
// Define class with private method
MyClass {
private secretState = 'hidden';
private doSomethingInternal() {
// implementation
}
}
// Create new instance of class.
const instance = new MyClass();
// Use our MakePublic utility to allow access to all methods.
const publicInstance = instance as MakePublic<MyClass>;
// Now fully type-safe with autocompletion
vi.spyOn(publicInstance, 'doSomethingInternal');
// NOTE: The currently used alternative to the above is a cast to any:
// vi.spyOn(instance as any, 'doSomethingInternal');
The use case is implementing a private generic class method that takes one of its own keys as a a parameter for updating one of any class members that implement a common type. Here is a trivial example:
// Does not work because keyof excludes private members
type NumericalKey= {
[K in keyof MyClass]: MyClass[K] extends number ? K : never;
}[keyof MyClass];
class MyClass {
private x = 1;
private y = 2;
private z = 3;
public doSomething() {
this.incrementNumericalMember('x');
this.incrementNumericalMember('y');
this.incrementNumericalMember('z');
}
private incrementNumericalMemberAndDoSomethingElse<K extends NumericalKey>(key: K) {
this[key]++;
doSomethingElseWith(this[key]);
}
}
@benwiley4000 I don't see what the problem is:
class MyClass {
private x = 1;
private y = 2;
private z = 3;
public incrementNumericalMember(key: 'x'|'y'|'z') {
this[key]++;
return this[key];
}
}
This works just fine. (playground)
I'd also like to point out that the proposal is currently insufficiently defined, just giving a way to enumerate private keys doesn't mean that they can be used to actually index the class:
class Foo {
private a = "";
public b = 1;
}
type FieldsOfFoo = "a" | "b" // or as proposed `fieldof Foo`
type PublicCopyOfFoo = {[K in FieldsOfFoo]: Foo[K]}
// !! ERROR !! ^^^^^^
// Type 'K' cannot be used to index type 'Foo'. (2536)
Playground Link. So it might make more sense to advocate for #22677 as that would actually produce the desired outcome.
Am not fan of type assertion expression for readability.
@jonlepage, ok what about this which is more or less identical to your thing but usable in a more generic way (Playground Link)
/**
* returns object unmodified with the readonly restrictions stripped
* is by no means safe to use in general
*/
function asWritable<T>(thing: T): { -readonly [P in keyof T]: T[P] }{
// will work until #13347 is addressed,
// at which point an "as any" will be needed here
return thing;
}
class Childrable {
public addChild(child: A) {
// BOOM! now doable
asWritable(child).parent = this.entity;
this.children.push(child);
}
public entity?: A;
public readonly children: A[] = [];
}
class A {
public readonly parent?: A
private field = "foo"
protected Renderer() { }
}
@katz12 you should just not have that Resolve type, filtering for Function tries to preserve call signatures but doesn't capture 'new-able' things, I touch on this here but that is talking about a 'NOP' type that is supposed to not actually modify the type given, just doing T & { [brandKey]: U } is definitely the right approach there.
As far as I can tell jimtendo's case is the only case that would actually be fixed by this proposal as they only need to enumerate the private keys, every other mentioned cases have easy work arounds and this feature wouldn't help at all as you'd still need a way to use the private/protected fields which is not covered by the proposal but is addressed by #22677