How can I describe type like
key is optional, but if it existed, it cannot be undefined.
At the first time, I'm using Partial to make all properties of T optional.
interface A {
a: number;
}
var data: A = {
a: 1,
}
var update1: Partial<A> = {
}
var update2: Partial<A> = {
a: undefined
}
var result1: A = {
...data,
...update1,
} // { a: 1 }
var result2: A = {
...data,
...update2,
} // { a: undefined }
The problem here is that result2 is not implementing interface A in runtime, but typescript never complains about it. Is it bug or feature? I guess typescript not working well with spread operator...
The goal is distinguish these two variable using typescript!
var data: T = {
a: 1,
b: 2,
}
var optional1: MyPartial<T> = { // Totally OK
}
var optional2: MyPartial<T> = { // OK
a: 3,
}
var optional3: MyPartial<T> = { // OK
b: 4,
}
var optional4: MyPartial<T> = { // OK
a: 3,
b: 4,
}
var undef1: MyPartial<T> = { // typescript must throw error
a: undefined,
}
var undef2: MyPartial<T> = { // typescript must throw error
a: 3,
b: undefined
}
...
Check this out TypeScript playground example.
Partial<T>for redux action creators so I don't need to include all of the props on theTobject (e.g., setting part of a User type while registering), but this allows me to potentially set the wrong property type :(