#Disallow usage of overlapping type

6 messages · Page 1 of 1 (latest)

twin frost
#

Is there a way of making the type PrivateUserData incompatible with PublicUserData in the following example, but without adding extra fields to neither of the two?

type PrivateUserData = {
  email: string;
  password: string;
}

type PublicUserData = {
  email: string;
}

function showToTheWorld(data: PublicUserData) {
  console.log(data);
} 

const superSecretData: PrivateUserData = {
  email: '[email protected]',
  password: 'password123'
};

showToTheWorld(superSecretData);
ebon maple
#

depending on why you want to avoid "adding" extra fields, this might qualify as a solution:

dark sentinelBOT
#
mkantor#0

Preview:```ts
type PrivateUserData = {
email: string
password: string
}

type PublicUserData = {
user: string
email?: never
password?: never
}

function showToTheWorld(data: PublicUserData) {
console.log(data)
}

const superSecretData: PrivateUserData = {
email: "[email protected]",
password: "password123",
}

showToTheWorld(superSecretData)```

ebon maple
#

if you haven't heard of it before i'd also suggest reading up on "branding". you might prefer that kind of approach

#

honestly though if you want to be 100% safe you'll need to whitelist/filter the displayed keys in showToTheWorld

dusty wharf
#

yeah, generally the answer is your question is no, but there is something called "branding" that can force this distinction to a limited extent