我试图摆脱我的 tslint 错误,Type declaration of 'any' loses type-safety.
但我正在努力弄清楚事件的正确类型是什么。
我正在通过 Lynda “构建和部署全栈 React 应用程序”,同时尝试将其转换为 Typescript。
以下是导致问题的具体线路:
onClick={(event: any) => {
makeMove(ownMark, event.target.index)
}}
我试图将事件声明为几种不同的类型,例如React.MouseEvent<HTMLElement>
,以及 HTMLElement 上的其他一些子类型,但没有成功,因为 target.index 不是我能想到的任何类型的属性。我可以从检查员看到 currentTarget 是 Konva.Text 并且索引设置为0
但不确定对我有帮助,因为我无法将类型设置为Konva.Text
,这对我来说很有意义,但这也不起作用。
这是我完整的 React 功能组件:
export const Squares = ({units, coordinates, gameState, win, gameOver, yourTurn, ownMark, move}: SquaresProps) => {
let squares = coordinates.map( (position: number, index: number) => {
let makeMove = move
let mark = gameState[index] !== 'z' ? gameState[index] : false
let fill = 'black'
// when someone wins you want the square to turn green
if (win && win.includes(index)) {
fill = 'lightGreen'
}
if (gameOver || !yourTurn || mark) {
makeMove = () => console.log('nope!')
}
return (
<Text
key={index}
x={position[0]}
y={position[1]}
fontSize={units}
width={units}
text={mark}
fill={fill}
fontFamily={'Helvetica'}
aligh={'center'}
onClick={(event: any) => {
makeMove(ownMark, event.target.index)
}}
/>
)
})
return (
<Layer>
{squares}
</Layer>
)
}
这是我的package.json
依赖项:
"dependencies": {
"konva": "^1.6.3",
"material-ui": "^0.18.4",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-konva": "^1.1.3",
"react-router": "~3.0.0",
"react-tap-event-plugin": "^2.0.1",
"styled-components": "^2.1.0"
},
我认为索引是由 Konva Layer 类添加的,但我对整个 React 生态系统还很陌生,所以仍然试图将我的大脑全部包裹起来。
更新:
我能够使用 Tyler Sebastion 的声明合并建议来定义使 tslint 静音的目标上的索引。我不确定这是最好的方法,因为它对我来说有点脆弱。
这是额外的接口代码和更新的 onclick 事件:
interface KonvaTextEventTarget extends EventTarget {
index: number
}
interface KonvaMouseEvent extends React.MouseEvent<HTMLElement> {
target: KonvaTextEventTarget
}
...
return (
<Text
key={index}
x={position[0]}
y={position[1]}
fontSize={units}
width={units}
text={mark}
fill={fill}
fontFamily={'Helvetica'}
aligh={'center'}
onClick={(event: KonvaMouseEvent) => {
makeMove(ownMark, event.target.index)
}}
/>
)