DEV Community

Discussion on: Advanced TypeScript: reinventing lodash.get

Collapse
 
rogerpadilla profile image
Roger Padilla

Thanks a lot for sharing this @tipsy_dev !

I'm building a library and this could be really useful there. Do you know if/how to add type-safety in the path of the properties via template literals? I mean, not to return undefined but to make the compiler ensure the path is a valid path.

E.g.

interface User {
  email?: string;
}

interface Group {
  name?: string;
  creator?: User;
}
Enter fullscreen mode Exit fullscreen mode

So if we do:

// compiles
GetFieldType<Group, 'creator.email'>;

// produces compilation error
GetFieldType<Group, 'creator.invalidPath'>;
Enter fullscreen mode Exit fullscreen mode

Is there a way to do this?