avdotion
avdotion

Reputation: 137

Multiple function's argument types

Trying to write typesafe code I have stuck on this issue. I want to pass inside my foo function one of two known exact config variations, but it falls with errors. Nevertheless it seems to be type safe.

type Config = {
  bar: string,
} | {
  baz: string,
};

const foo = (config: Config): string => {
  if (typeof config.bar === 'undefined') {
    return config.baz;
  }

  return config.bar;
};

foo({bar: 'test'});
Property 'bar' does not exist on type 'Config'. Property 'bar' does not exist on type '{ baz: string; }'.
Property 'baz' does not exist on type 'Config'. Property 'baz' does not exist on type '{ bar: string; }'.
Property 'bar' does not exist on type 'Config'. Property 'bar' does not exist on type '{ baz: string; }'.

Typescript playground link.

Help to figure out, how to write typesafe code like that, with exact configurations for a single argument.

Upvotes: 0

Views: 62

Answers (2)

Vignesh Murugan
Vignesh Murugan

Reputation: 575

You can do the following

type Bar = { bar: string }
type Baz = { baz: string }
type Config = Bar | Baz;

const hasBaz = (config: Config): config is Baz => {
 return (config as Baz).baz !== undefined;
}

const foo = (config: Config): string => {
   return hasBaz(config) ? config.baz : config.bar
};

foo({baz: 'test'});

Upvotes: 2

Terminat
Terminat

Reputation: 1237

You can use in operator to check if the property is present on the object

type Config = {
  bar: string,
} | {
  baz: string,
};

const foo = (config: Config): string => {
  if ("baz" in config) {
    return config.baz;
  }

  return config.bar;
};

foo({bar: 'test'});

Upvotes: 2

Related Questions