学习 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
应用程序.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} />
我注意到通过检查 Text 组件的 style 属性:
style?: TextStyle | Partial<ITextStyle> | undefined
所以基本上上面完成的所有打字都可以工作。
检查此沙箱以查看功能代码:https : //codesandbox.io/s/elastic-platform-zzvnb
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句