Max Lascombe
Max Lascombe

Reputation: 31

In Typescript, how to check that if a key is present in an object, so should another one

This seems really silly and basic but for some reason I can't get it to work.

I want a type for a function argument to be an object that always has a key a of type string. This object can also have a key b of type string, but if it has this key, it must also have key c of type string.

Essentially, the function should have one argument of type

{ a: string } or { a: string, b: string, c: string }.

I therefore want this to show an error if the object I pass the function is { a: 'abc', b: 'abc' } because it is missing c.

My initial thought was something like this:

{ a: string } | { a: string, b: string, c: string }

But this doesn't give me the error I am looking for. I've done some research online, but to no avail. Any ideas?

Also chatgpt was not helpful...

Upvotes: 1

Views: 21

Answers (0)

Related Questions