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?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744299304a4567418.html
评论列表(0条)