Here is an even more generic solution to any type (not just User):
typeConfig<Typeextendsobject>={[keyinkeyofType]-?:boolean;};typeTrueKeys<Typeextendsobject,ConfextendsConfig<Type>>={[keyinkeyofConf]:Conf[key]extendstrue?key:never}[keyofType]typeGet<Typeextendsobject>=<ConfextendsConfig<Type>>(config:Conf)=>Required<Pick<Type,TrueKeys<Type,Conf>>>;typeUser={name?:string;lastname?:string;age:number;};typeUserConfig=Config<User>// Here declaration to be changed 🔥declareconstgetUser:Get<User>// test casesconstuser=getUser({name:true,lastname:false,age:false})user.name.toLocaleLowerCase()// this field should be non-optionaluser.lastname// this field should not be there and we should have compile error 🛑user.age// this field should not be there and we should have compile error 🛑constuser2=getUser({name:true,lastname:true,age:true})user2.name.toLocaleLowerCase()// this field should be non-optionaluser2.lastname.toLocaleLowerCase()// this field should be non-optionaluser2.age.toFixed()// this field should be non-optionalconstuser3=getUser({name:false,lastname:true,age:false})user3.name// this field should not be there and we should have compile error 🛑user3.lastname.toLocaleLowerCase()// this field should be non-optionaluser3.age// this field should not be there and we should have compile error 🛑constuser4=getUser({name:false,lastname:false,age:true})user4.name// this field should not be there and we should have compile error 🛑user4.lastname// this field should not be there and we should have compile error 🛑user4.age.toFixed()// this field should be non-optionalconstuser5=getUser({name:false,lastname:false,age:false})user5// user4 should be empty object {}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Here is an even more generic solution to any type (not just User):