Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a type that must include some properties, but be ok with it including additional properties?

I have a util function whose first parameter param must include (simplified for example) the properties param.X and param.Y, but it doesn’t matter what other properties it has. For instance it can also have param.Z but that’s not used by the util function and can be ignored.

How can I type the param such that it enforces this constraint without complaining something like Z not found on type ParamType?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Intersect the object type with Record<keyof any, unknown>.

const fn = (obj: { x: string; y: string } & Record<keyof any, unknown>) => {
};

fn({x: 'x'}) // Fails
fn({x: 'x', y: 'y'}) // Passes
fn({x: 'x', y: 'y', z: 'z'}) // Passes
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading