简体   繁体   English

Typescript 对象成员的内联类型声明

[英]Typescript inline type declaration for object-member

In the following block of code defined the type of the attribute pens with the <> -Notation:在以下代码块中,使用<> -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:上面的代码有效,但我的 linter 抱怨这个类型提示应该以不同的方式声明:

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.正如错误所说 - 使用as而不是尖括号表示法来断言类型。

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?但我认为这不是你想要的——你真的想告诉 TS 创建的数组是一个tuple ,只有一个项目吗? Since you're creating 5 elements, you probably want an array type instead.由于您要创建 5 个元素,因此您可能需要一个数组类型。

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.如果是这种情况,也根本不需要类型断言 - TS 可以正确推断出创建的数组是所需的类型。

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.它在根本没有任何 TypeScript 语法的情况下推断出正确的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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