Search code examples
javascripttypescriptlambdaobject-initialization

How to initialize and return an object in a single line


I am trying to create Option objects based on the following typed interface:

interface Option {
    /** Text for rendering */
    label: string;
    /** Value for searching */
    value: string | number;
    /**
     * Allow this option to be cleared
     * @default true
     */
    clearableValue?: boolean;
}

Is it possible to convert the following to a single line?

const options = [1, 2, 3].map<Option>((t) => {
    const option: Option = { label: String(t), value: String(t) };
    return option;
});

I tried:

const options = [1, 2, 3].map<Option>((t) => Option = { label: String(t), value: String(t) });

but it doesn't work.


Solution

  • You're almost there:

    const options = [1, 2, 3].map(t => <Option>{ label: String(t), value: String(t) });
    

    Type assertion <Option>{ label: String(t), value: String(t) } can also be done with as operator: t => ({ label: String(t), value: String(t) }) as Option

    Update: As you've already figured out - the first option (<Option>) creates ambiguity in *.tsx files, so as syntax is preferred.