Trying to implement this code:
type A = {
b: false,
} | {
b: true,
p: string;
}
function createA(b: boolean, p: string | undefined): A {
if (b && p === undefined) {
throw 'Error';
}
const a: A = {
b,
p,
}
return a;
}
Encountering an error when creating a
:
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
Understanding that p
may not be defined at this point.
A possible fix could involve making the code more explicit:
function createAFixed(b: boolean, p: string | undefined): A {
let a: A;
if (!b) {
a = { b };
} else {
if (p) {
a = { b, p };
} else {
throw 'Error';
}
}
return a;
}
Contemplating if there is a "better way" to handle this situation.
Is it possible to use a single conditional and assignment to create a
?