Home > Net >  Typescript inline type declaration for object-member
Typescript inline type declaration for object-member

Time:12-28

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?

CodePudding user response:

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.

  • Related