Home > Software design >  React typescript optional parameter
React typescript optional parameter

Time:11-09

New to react/typescript. I am trying to create a function with a typscripted param.

example:

export function get_prod(category: string) { ...}

The problem is I have 2 product scenarios. One can have an optional category, the other type requires a category to only load products from that category but otherwise the function is almost identical.

I wanted to do something like this:

if category = 'ebook' {
    arg = 'category: string'
} else
    arg = 'category?: string'
}

export function get_prod(arg) { ...}

What's the best way to handle this?

CodePudding user response:

You could use type aliases to define custom types and accept their union as a parameter (basically, either one). For example:

type Book = { category: string };
type Other = { id: number, category?: string };

const getProduct = (product: Book | Other) => {
    // ...
};

CodePudding user response:

i think you have to use overloads like this:

type TProduct = {
    productName: string
    id: number
};

function getProduct(category: 'ebook'): TProduct
function getProduct(id: number, category?: string): TProduct
function getProduct(category?: any, id: any): TProduct {
    return { productName: 'productName', id: 123 };
}

const productA = getProduct(123);
const productB = getProduct(123, 'dasdsa');
const productC = getProduct('ebook');

CodePudding user response:

type Params = {category: 'ebook'} | {category?: string; otherParam: unknown};
export function get_prod(arg: Params) { ...}
  • Related