0

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.

Erwin Mayer
  • 18,076
  • 9
  • 88
  • 126

2 Answers2

1

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.

Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
  • The first suggestion has an error: "Symbol 'label' cannot be properly resolved, probably it is located in inaccessible module". Is it normal? I am using TypeScript 1.8. The second suggestion works fine. – Erwin Mayer Nov 02 '16 at 07:42
  • Try to put object initializer into brackets ` – Aleksey L. Nov 02 '16 at 08:01
  • No it doesn't help. Maybe this wasn't supported before TS2. Unless there is a way to make it work, you could update your reply to differentiate between the two versions and I'll mark it as accepted. – Erwin Mayer Nov 02 '16 at 08:04
  • Indeed, it seems due to the fact that I am in a *.tsx file and – Erwin Mayer Nov 02 '16 at 15:09
  • https://basarat.gitbooks.io/typescript/content/docs/tips/genericTSX.html – Erwin Mayer Nov 02 '16 at 15:11
  • A bit hackish, there doesn't seem to be a good solution. If you can update your answer to reflect that it'll probably save some time to people. – Erwin Mayer Nov 02 '16 at 15:13
0

You could use a typescript cast:

const options = [1, 2, 3].map<Option>((t) => <Option>{ label: String(t), value: String(t) } );
CortoMaltese
  • 131
  • 6
  • This triggers an error: "Symbol 'label' cannot be properly resolved, probably it is located in inaccessible module". Is it normal? I am using TypeScript 1.8. – Erwin Mayer Nov 02 '16 at 07:42
  • I tried it in the typescript playground without any errors. I am sorry that this obviously does not work in your environment. – CortoMaltese Nov 02 '16 at 08:05