I am currently working on implementing the concept of initializing C# Class objects in a TypeScript class. However, I encountered an error message from the compiler as follows.
Error: Type 'string | number | null | undefined' is not compatible with type 'null'. Error: Type 'undefined' cannot be assigned to type 'null'
Below you can find the code snippet:
type gender = 'Male' | 'female';
class Person {
public name: string | null = null;
public age: number | null = null;
public gender: gender | null = null;
constructor(
param: Partial<Person>
) {
if (param) {
/**
* Checks if key exists in Person
* @param key
*/
const keyExists = (k: string): k is keyof Person => k in this;
/**
* List of keys
*/
const keys: string[] = Object.keys(param);
keys.forEach((k: string) => {
if (keyExists(k)) {
//k: "name" | "age" | "gender"
const value = param[k]; //value: string | number | null | undefined
//let a = this[k]; //a: string | number | null
this[k] = value; //error : Type 'string | number | null | undefined' is not assignable to type 'null'.
// Error : Type 'undefined' is not assignable to type 'null'.
}
});
}
}
}
let a = new Person({
age: 10
});
console.log(a);
Below is the content of tsconfig.json file:
{
"compilerOptions": {
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
"strict": true, /* Enable all strict type-checking options. */
"strictNullChecks": true, /* Enable strict null checks. */
"baseUrl": "./", /* Base directory to resolve non-absolute module names. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
}
}