Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript inline type declaration for object-member

In the following block of code defined the type of the attribute pens with the <>-Notation:

return {
    ...defaultValues, 
    pens: 
      <[{penStrokeColor: string, penStrokeWidth: number, penOpacity: number}]>
      [...Array(5).keys() ].map((_)=> { 
        return {
          penStrokeColor: defaultValues.currentItemStrokeColor,
          penStrokeWidth: defaultValues.currentItemStrokeWidth,
          penOpacity: defaultValues.currentItemOpacity
        }})
  }

The code above works but my linter is complaining that this type-hint should be declared differently:

Use 'as [{ penStrokeColor: string; penStrokeWidth: number; penOpacity: number }]' instead of '<[{ penStrokeColor: string; penStrokeWidth: number; penOpacity: number }]>'  @typescript-eslint/consistent-type-assertions

Can this be done inline as well and if so, how?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s just as the error says – use as instead of angle bracket notation to assert the type.

return {
    ...defaultValues, 
    pens: 
      [...Array(5).keys() ].map((_)=> { 
        return {
          penStrokeColor: defaultValues.currentItemStrokeColor,
          penStrokeWidth: defaultValues.currentItemStrokeWidth,
          penOpacity: defaultValues.currentItemOpacity
        }}) as [{penStrokeColor: string, penStrokeWidth: number, penOpacity: number}]
  }

But I don’t think that’s what you want – do you really want to tell TS that the created array is a tuple, with only a single item? Since you’re creating 5 elements, you probably want an array type instead.

There’s also no need for type assertion at all if that’s the case – TS can properly infer that the created array is of the desired type.

return {
    ...defaultValues, 
    pens: [...Array(5).keys() ].map((_)=> { 
        return {
          penStrokeColor: defaultValues.currentItemStrokeColor,
          penStrokeWidth: defaultValues.currentItemStrokeWidth,
          penOpacity: defaultValues.currentItemOpacity
        };
    })
};

which infers the correct type without any TypeScript syntax at all.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading