#make two properties required if one of them exist

17 messages · Page 1 of 1 (latest)

covert oasis
#

it may be a big mandela effect, but afaik this should do it

export type Dependency =
    | {
          groupId: string
          artifactId: string
      }
    | {
          repoId: string
          repoUrl: string
          groupId: string
          artifactId: string
      }

meaning, {groupId: '', artifactId: ''} should be valid, {repoId: '', repoUrl: '', groupId: '', artifactId: ''} should be valid too, but {repoId: '', groupId: '', artifactId: ''} should not be valid, bc the repoUrl is missing, and viceversa. but for some reason, this is valid, no errors

const x: Dependency = {repoUrl: '', groupId: '', artifactId: ''}

why? is that normal? i already restarted the TS lsp, it depends on some setting in tsconfig.json? if not, how can i achieve that then?

arctic tiger
#

Yes it's normal, because TS does not care about excess properties.

#

So { repoId: '', groupId: '', artifactId: '' } is treated as { groupId: string, artifactId: string } variant with an excess property of repoId.

#

What you probably want is a DU.

covert oasis
#

since when? is that configurable in any way?

arctic tiger
#

It's always been like this, it's how TS works.

#

!hb discriminated

dry hillBOT
arctic tiger
#

But yeah DU is probably what you want ^

covert oasis
#

so i need to add another property to differentiate them?

#

i dont like that behavior at all

#

is that normal in other languages too?

arctic tiger
#

Depends on the language, a lot of languages don't even support union type.

covert oasis
#

yea

#

but

#

thats just so weird

arctic tiger
#

But DU is the proper way to do what you want in TS.