admin管理员组文章数量:1431955
type padding = [number, number, number, number]
interface IPaddingProps {
defaultValue?: padding
className?: string
disabled?: boolean
min?: number
max?: number
onChange?: (value: number | string) => void
}
interface IFieldSate {
value: padding
}
export default class FieldPadding extends React.Component<IPaddingProps, IFieldSate> {
readonly state = {
value: [0, 0, 0, 0]
}
constructor(props: IPaddingProps) {
super(props)
if (props.defaultValue) {
this.state.value = [...props.defaultValue]
}
}
}
I get an error at state
saying:
Type 'number[]' is missing the following properties from type '[number, number, number, number]': 0, 1, 2, 3?
type padding = [number, number, number, number]
interface IPaddingProps {
defaultValue?: padding
className?: string
disabled?: boolean
min?: number
max?: number
onChange?: (value: number | string) => void
}
interface IFieldSate {
value: padding
}
export default class FieldPadding extends React.Component<IPaddingProps, IFieldSate> {
readonly state = {
value: [0, 0, 0, 0]
}
constructor(props: IPaddingProps) {
super(props)
if (props.defaultValue) {
this.state.value = [...props.defaultValue]
}
}
}
I get an error at state
saying:
Share Improve this question edited Feb 28, 2019 at 2:28 Sky Clong asked Feb 23, 2019 at 5:41 Sky ClongSky Clong 1612 silver badges9 bronze badges 2Type 'number[]' is missing the following properties from type '[number, number, number, number]': 0, 1, 2, 3?
- Are you sure the error is occurring in the above code. Because you sure don't seem be to setting numbers 0, 1, ,2, 3 – Shubham Khatri Commented Feb 23, 2019 at 6:13
- 1 @ShubhamKhatri The error message talks about properties, not their values – Bergi Commented Feb 23, 2019 at 14:33
2 Answers
Reset to default 5Your problem is that state
is being inferred as an array instead of as a tuple. There are several ways around this, as detailed in this answer. I'll just present one of them here.
Assuming you are using TypeScript 3.0 or above, you can define the following tuple()
helper function which takes any number of arguments and returns a tuple of those arguments:
type Narrowable = string | number | boolean | undefined | null | void | {};
const tuple = <T extends Narrowable[]>(...t: T)=> t;
Then, you can use it inside your FieldPadding
class definition:
export default class FieldPadding extends React.Component<IPaddingProps, IFieldSate> {
readonly state = {
value: tuple(0, 0, 0, 0)
}
}
and that gives value
the type [0, 0, 0, 0]
, a tuple type with four elements of numeric literal type 0
.
UPDATE:
So you want state
to be readonly
but you want to change the values of state.value
from 0
to other numbers?
本文标签:
版权声明:本文标题:javascript - Type 'number[]' is missing the following properties from type '[number, number, number, num 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744299303a2599499.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论