After testing various scenarios, the comment by @jcalz helped to pass all test cases, where if we add type as number or null.
const var1: number | null = null;
function test(param1:number | null){
console.log(param1);
}
test(var1);
Answer from Raviraj Gardi on Stack OverflowMaybe<number> null vs undefined
How to declare a type as nullable in TypeScript? - Stack Overflow
Allow null to be used like a number in typescript - Stack Overflow
Docs: [strict-boolean-expressions] nullable number as wrong 'undefined' type
Maybe our GraphQL schema is bad, I don't know. I just work on the frontend.
I'm having problems like this when I turn strict non-null checks on:
Type 'Maybe<number>' is not assignable to type 'number | undefined'. Type 'null' is not assignable to type 'number | undefined'.ts(2322)
Variable that I have is from GraphQL codegen: Maybe<number>
I want to put it into here?: number;
Can I do something graphQL codegen settings? Preferably.
I can't play with the schema itself, not easily.
I can't change the whole app and turn everything into here?: number | null; that is too verbose and feels stupid, there must be a better way.
All fields in JavaScript (and in TypeScript) can have the value null or undefined.
You can make the field optional which is different from nullable.
interface Employee1 {
name: string;
salary: number;
}
var a: Employee1 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee1 = { name: 'Bob' }; // Not OK, you must have 'salary'
var c: Employee1 = { name: 'Bob', salary: undefined }; // OK
var d: Employee1 = { name: null, salary: undefined }; // OK
// OK
class SomeEmployeeA implements Employee1 {
public name = 'Bob';
public salary = 40000;
}
// Not OK: Must have 'salary'
class SomeEmployeeB implements Employee1 {
public name: string;
}
Compare with:
interface Employee2 {
name: string;
salary?: number;
}
var a: Employee2 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee2 = { name: 'Bob' }; // OK
var c: Employee2 = { name: 'Bob', salary: undefined }; // OK
var d: Employee2 = { name: null, salary: 'bob' }; // Not OK, salary must be a number
// OK, but doesn't make too much sense
class SomeEmployeeA implements Employee2 {
public name = 'Bob';
}
To be more C# like, define the Nullable type like this:
type Nullable<T> = T | null;
interface Employee{
id: number;
name: string;
salary: Nullable<number>;
}
Bonus:
To make Nullable behave like a built in Typescript type, define it in a global.d.ts definition file in the root source folder. This path worked for me: /src/global.d.ts