Is there a way to make a type optional in Typescript?
Here is the code snippet I am using:
const A = <T>(value: T) => new Clazz(value);
const B = <U>(value: U) => new Clazz(undefined, value);
class Clazz<T, U> {
constructor(private a?: T, private b?: U) {}
public map<Z>(callback: (value: T) => Z): Clazz<Z, U> {
return this.a
? A(callback(this.a))
: B(this.b);
}
}
However, this code is throwing an error:
Type 'Clazz<Z, {}> | Clazz<undefined, U | undefined>' is not assignable to type 'Clazz<Z, U>'.
Type 'Clazz<Z, {}>' is not assignable to type 'Clazz<Z, U>'.
Type '{}' is not assignable to type 'U'.
What would be the most effective solution to resolve this issue?
This is how my tsconfig.json
file is configured:
{
"compilerOptions": {
"baseUrl": "",
"declaration": true,
"lib": ["es6", "dom"],
"mapRoot": "./src",
"module": "es2015",
"moduleResolution": "node",
"noEmitHelpers": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"outDir": "./dist",
"sourceMap": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"target": "es2015",
"typeRoots": [
"./node_modules/@types"
]
}
}