0

I have the next structure

type child = {
    id:string;
    // other props
};
type parent = {
    children: ReactElement<child>[];
    onSelect:(val: /* literals of children ids ("id1" | "id2"...) */) =>void;
}

So as I imagine it, it would be good to have "this" type to allow to refer to the field of itself. So if I pass children with id1 and id2 as props to parent component, it could get its literal types and type of "onSelect" argument would be not just string, but literal types of ids of children

I found ThisParameterType and ThisType in typescript utilities, but those "this" are not type's this. Right? Is there a way to do it in ts?

VVS232
  • 43
  • 5
  • you can use `keyof` keyword to allow any property as long as it part of the type. See this question for more info: https://stackoverflow.com/questions/57337598/in-typescript-what-do-extends-keyof-and-in-keyof-mean – nbokmans Aug 09 '22 at 13:50
  • If I go with keyof - it will find that type of "keyof child.id" is string and will not infer EXACT ids of children as type literals – VVS232 Aug 09 '22 at 13:52
  • Well, you defined it as string. You should use the ID as a discriminator and make the child type a union of the specific children types. As you wrote it now, TS has no way of knowing which id's are possible. – pascalpuetz Aug 09 '22 at 13:54
  • You need to know the possible values of ID to create a type based on that – Roberto Aug 09 '22 at 14:01
  • So... no way to infer it at compile time? That's sad to hear. But thanks anyway – VVS232 Aug 09 '22 at 14:04
  • At "compile-time" there is no problem, but what you want is at "run-time", if I understood correctly – Roberto Aug 09 '22 at 16:33

0 Answers0