Home > other >  Custom type won't let access the object properties
Custom type won't let access the object properties

Time:07-04

I created a custom type with an object and a primitive type. in one place I want to check whether my value contains the object property or not. below are my types

export type FileTypePrimitive = string | null;

export type FileType = { name: string; url: string };

export type GenratedKey = FileType| FileTypePrimitive;

Inhere I want to check that keysToSend contains name or url properties.

const keysToSend = genratedFileKeys() // return GenratedKey Type
const url = keysToSend.name ? keysToSend.url : keysToSend; // throws error Property 
// 'name' does not exist on type 'string | FileType'.

CodePudding user response:

You can use typeof operator to determine whether keysToSend belongs to one of two primitive types being defined as FileTypePrimitive. If it doesn't then TypeScript will infer that it is FileType:

const url = typeof keysToSend === "string" || keysToSend === null ? keysToSend : keysToSend.url;

Playground

Typically, you would use the in operator but unfortunately it doesn't work on unions of primitive types (Typescript 4.2)

CodePudding user response:

it's given you that error because the variable keysToSend may be a string so it will not have the property name or url inside of it. you should check the variable type before you access the properties inside of it.

const url = typeof keysToSend === "string" ||keysToSend == null ? keysToSend : keysToSend.url;
  • Related