Sometimes, we want to fix the error ‘"TS2322: Type ‘Timeout’ is not assignable to type ‘number’" when running unit tests with TypeScript.
In this article, we’ll look at how to fix the error ‘"TS2322: Type ‘Timeout’ is not assignable to type ‘number’" when running unit tests with TypeScript.
How to fix the error ‘"TS2322: Type ‘Timeout’ is not assignable to type ‘number’" when running unit tests with TypeScript?
To fix the error ‘"TS2322: Type ‘Timeout’ is not assignable to type ‘number’" when running unit tests’ with TypeScript, we can define the type of the value returned by setTimeout
.
For instance, we write
let timeoutId: null | ReturnType<typeof setTimeout> = null;
timeoutId = setTimeout(() => {
//...
});
to set the timeoutId
to the null | ReturnType<typeof setTimeout>
union type.
We use typeof setTimeout
to get the type for the setTimeout
function.
And we use ReturnType
to get the return type of the setTimeout
function.
Then we can assign the value returned by setTimeout
to timeoutId
without error.
Conclusion
To fix the error ‘"TS2322: Type ‘Timeout’ is not assignable to type ‘number’" when running unit tests’ with TypeScript, we can define the type of the value returned by setTimeout
.