简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM