如何在 TypeScript 中的对象常量内分配 属性 类型?

How to assign a property a type inside an object constant in TypeScript?

正在学习 TypeScript,我想知道当 TypeScript 不能正确推断 属性 类型时,是否有一种简单的内联方式来表示对象常量内的类型?

错误信息:

Type '{ align: string; fontWeight: string; dropShadow: boolean; dropShadowAlpha: number; wordWrap: boolean; fill: string[]; }' is not assignable to type 'TextStyle | Partial<ITextStyle> | undefined'.
  Type '{ align: string; fontWeight: string; dropShadow: boolean; dropShadowAlpha: number; wordWrap: boolean; fill: string[]; }' is not assignable to type 'Partial<ITextStyle>'.
    Types of property 'align' are incompatible.
      Type 'string' is not assignable to type 'TextStyleAlign | undefined'.ts(2322)

在我用 textStyleAlign 和 textStyleFontWeight 替换原来的 align 和 fontWeight 值之前收到此错误消息。

我是如何创建这个例子的:

yarn create react-app app-name --template typescript
cd app-name
yarn add pixi.js
yarn add @inlet/react-pixi

App.tsx

import { Stage, Text} from '@inlet/react-pixi';
import type { TextStyleAlign, TextStyleFontWeight } from '@pixi/text';

const textStyleAlign : TextStyleAlign = 'center';
const textStyleFontWeight : TextStyleFontWeight = '900';

const textStyle = {
  align: textStyleAlign,
  // align: 'center',   // <- why can't I put this instead?
  fontWeight: textStyleFontWeight,
  // fontWeight: '900', // <- same here
  dropShadow: true,
  dropShadowAlpha: 0.6,
  wordWrap: true,
  fill: ["white", "#cccccc"]
}

function App() {
  return (
    <Stage>
      <Text
        text={`Hi World`}
        style={textStyle}
      />
    </Stage>
  );
}

export default App;

嘿,看看你需要像这样传递 TextStyle 实例的文档:

const textStyle = new TextStyle({
  align: "center",
  fontWeight: "900",
  dropShadow: true,
  dropShadowAlpha: 0.6,
  wordWrap: true,
  fill: ["white", "#cccccc"]
});

如果您不想创建该实例,您可以这样做:

import { ITextStyle, TextStyle } from "pixi.js";

// The style prop also takes a Partial of ITextStyle so by typing the const like that you would achieve the typing correctly
const textStyle: Partial<ITextStyle> = {
  align: "center",
  fontWeight: "900",
  dropShadow: true,
  dropShadowAlpha: 0.6,
  wordWrap: true,
  fill: ["white", "#cccccc"]
};

如果你想让它像你发布的代码那么你可以像这样使用 as 类型断言

const textStyle = {
  align: "center" as TextStyleAlign,
  fontWeight: "900" as TextStyleFontWeight,
  dropShadow: true,
  dropShadowAlpha: 0.6,
  wordWrap: true,
  fill: ["white", "#cccccc"]
};

如果您通过这 3 种方法中的任何一种,您将不会遇到类型问题:

<Text text="Hi World" style={textStyle} />

我注意到通过检查文本组件的样式属性:

style?: TextStyle | Partial<ITextStyle> | undefined

所以基本上上面的所有输入都可以。

检查此沙箱以查看功能代码:https://codesandbox.io/s/elastic-platform-zzvnb

因为align只有三种类型:'left'、'center'或'right':https://pixijs.download/dev/docs/PIXI.TextStyle.html#align

所以如果你想使用对齐,你需要确保它有这些类型。不是值为 center 的字符串。您可以使用 TextStyleAlign 来声明类型。或者 const textStyleAlign : 'center' = 'center';.

如果您不想这样声明类型。您可以使用 new TextStyle()https://reactpixi.org/components/text

style={
  new TextStyle({
    align: 'center',
    ...
  })
}