Erwin Mayer Erwin Mayer - 1 month ago 6
TypeScript Question

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.

Answer

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)