My goal is to set default values for all properties in my custom type if they are not defined.
This is what I have done:
// custom type with optional properties
type MyType = {
// an example property:
str?: string
}
// with numerous properties, assigning them individually is not feasible
// hence, default values object was created
const defaultValuesForMyType: MyType = {
str: "hello world!"
}
// function that performs actions with a string input
function doThingsWithString(str: string): void {
console.log(str);
}
// function that takes an object of custom type as input
function driver(inputObject: MyType) {
const finalObject: MyType = { ...defaultValuesForMyType, ...inputObject };
doThingsWithString(finalObject.str);
}
However, VS Code displays the error:
doThingsWithString(finalObject.str);
^~~~~~~~~~~~~~^
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'. ts(2345)
const finalObject: {
str?: string | undefined;
}
I believed that finalObject cannot be undefined
, right? 🤔
edited:
@jcalz's solution did the trick!
I realized it was a class issue, my mistake 😅
// my custom type with all optional properties
type MyType = {
// an example property:
str?: string
}
// imagine I have hundreds of properties, I can't assign all of them one by one
// so I created a object for default values
const defaultValuesForMyType = {
str: "hello world!"
}
// passes a string to do something
// imagine it's a function in other API that I can't change
function doThingsWithString(str: string): void {
// do something, doesn't matter, for example:
console.log(str);
}
class TestClass {
propObject;
driver(inputObject: MyType) {
this.propObject = { ...defaultValuesForMyType, ...inputObject };
doThingsWithString(this.propObject.str);
}
}
No error, but VS Code now indicates that TestClass#propObject
is of type any