This come with a debate with my colleague that I'm using nullable object type.
type Value = Node | null
const [v0, setV0] = React.useState<Value>(null)
const [v1, setV1] = React.useState<Value>(null)
const snapshot = (nodes: Node[]) => {
const root = Parser.parse(nodes)
if (v0 === null) {
setV0(root)
} else if (v1 === null) {
setV1(root)
} else {
setV0(v1)
setV1(root)
}
alert("current version saved!")
}
He's suggestion is change it to undefinable object type. type Value = Node | undefined
since null is a mistake
My understanding with undefined
type in JS is a preserve type for item not found. ie,
object['not exist'] === undefined
array[-1] === undefined
With his suggestion we cannot distinguish if
type object = { [key: string]: Value }
object['not exist'] === undefined
const a: Value = object['not exist']
Also many libraries like lodash treat undefined and null differently. So I'm worried if this can cause problems later on.
Node | undefined
is the same sort of a mistake, for the same reason - it's only that it's slightly different in flavor. So your colleague's argument kind of doesn't hold up. But see what semantically makes more sense -null
orundefined
- and consider how your type is going to be used.