Understanding How to Get Property Names in a Union Class

Asked 1 years ago, Updated 1 years ago, 73 views

First, prepare two class-based components.

class AdminInfoComponent {
  public userCount: number = 0;
}
class UserComponent {
  public id:string="";
  public createdAt: number = 0;
}

Next, create a type to get the property (component field) name of the class.

type ExtractFields <T>={
  Key of T—K
}[keyofT];

Note:
https://stackoverflow.com/questions/55479658/how-to-create-a-type-excluding-instance-methods-from-a-class-in-typescript

For example, if you apply this type to each component (class):

let test1: ExtractFields <AdminInfoComponent>;// "userCount"
let test2: ExtractFields <UserComponent >// "userID" | "createdAt"

Now, I checked to see if the components that I set to type can be executed successfully even if they are Unionized (two or more cases).

let test3: ExtractFields <AdminInfoComponent | UserComponent >;// NEVER

It was an unexpected never.Expected (desired) type: "userCount" | "userID" | "createdAt"

I don't know why it's never, and I don't know where to modify to return the model I was looking for, so I asked you a question.
Thank you for your cooperation.

typescript

2022-09-30 19:57

1 Answers

I think this is the type you want.

let test3: ExtractFields <AdminInfoComponent > | ExtractFields <UserComponent >

I think there are some parts of the question that I have omitted, but if not, I think a simple keyof can replace ExtractFields

let test1:keyofAdminInfoComponent
let test2 —key of UserComponent
let test3 —keyofAdminInfoComponent | keyofUserComponent


2022-09-30 19:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.