作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我必须将 React 应用程序转换为 Typescript,但我不知道如何设置哈希对象的初始状态。
原始js
export default class Wizard extends PureComponent {
constructor(props) {
super(props);
this.state = this.initialState();
}
/** Setup Steps */
initialState = () => {
const state = {
activeStep: 0,
hashKeys: {},
};
// Set initial classes
// Get hash only in client side
const hash = typeof window === 'object' ? this.getHash() : '';
const children = React.Children.toArray(this.getSteps());
children.forEach((child, i) => {
// Create hashKey map
state.hashKeys[i] = (child.props && child.props.hashKey) || `step${i + 1}`;
state.hashKeys[state.hashKeys[i]] = i;
});
...
return state;
}
...
我失败的尝试
export interface TState {
activeStep?: number
hashKeys: {
[key: number]: string
}
}
export default class StepWizard extends PureComponent<{},TState> {
constructor(props: IStepWizardProps) {
super(props)
this.state = this.initialState()
}
initialState = () => {
const state = {
activeStep: 0,
hashKeys: {}, /* <---- This seems to be the problem */
}
// Set initial classes
// Get hash only in client side
const hash = typeof window === "object" ? this.getHash() : ""
const children = React.Children.toArray(this.getSteps())
children.forEach((child, i) => {
// Create hashKey map
// the following give a TS error
// ERROR: (property) hashKeys: {}
// Element implicitly has an 'any' type because expression of type 'number'
// can't be used to index type '{}'.
// No index signature with a parameter of type 'number' was found on type '{}'.ts(7053)
state.hashKeys[i] = (child.props && child.props.hashKey) || `step${i + 1}`
state.hashKeys[state.hashKeys[i]] = i
})
...
我得到 state.hasKeys[i]
(属性)hashKeys:{}元素隐式具有“任何”类型,因为类型“数字”的表达式不能用于索引类型“{}”。 在类型“{}”上找不到参数类型为“数字”的索引签名。ts(7053)
最佳答案
问题似乎出在将 hashKeys 定义为 {}
。
Typescript 不知道键/值的数据类型是什么,但是,您可以告诉它!
const hashKeys = {} as Record<number, string>;
const x = hashKeys[0];
以你的例子为例:
const state = {
activeStep: 0,
hashKeys: {} as Record<string, string>, // or whatever your types are
};
关于reactjs - 如何为 TypeScript React 应用程序设置键/值默认状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62139738/
我是一名优秀的程序员,十分优秀!