when you create a typescript interface with an optional property like this:
interface X {
a?: string
}
here x.a is of type string | undefined
so typescript will complain of the following code:
function stringValue(value: string):void{}
function test(x:X){
// error, because stringValue() only accepts strings
stringValue(x.a)
}
but, if Typescript knows x.a value in advance, why it still complains?
function test(x:X){
x = { a:"string value" }
// now x.a is string, not string | undefined
// so the following code must be valid
// but TS still complains
stringValue(x.a)
// this is a workaround but out of my question's scope
stringValue(x.a as string)
}
how to tell typescript that the consumer of our function doesn't have to provide a value for x.a
but we assign a default value to it, so it cannot be an undefined.