Type 'Timer' is not assignable to type 'null' in typescript

János

I use this code:

const clearTimer = (e: any) => {
    setTimer(<div></div>);
    if (Ref.current) clearInterval(Ref.current);
    startTimer(e);
    const id = setInterval(() => {
        startTimer(e);
    }, 1000)
    Ref.current = id;
}

For Ref.current = id; I get this error:

(property) MutableRefObject<null>.current: null

Type 'Timer' is not assignable to type 'null'.

And these lines not solved my problem:

Ref.current = id.toString();
Ref.current = id ?? '';
matin turkaman

When using useRef with Typescript, you should provide a generic argument to specify what is the expected type of the held value.

In your case:

const Ref = useRef<Timer>(null);

Then Ref.current can be assigned to the result of setInterval.

See this article for more info: https://linguinecode.com/post/how-to-use-react-useref-with-typescript

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Typescript: Type 'Timer' is not assignable to type 'null'

Typescript: Type 'number | null' is not assignable to type 'number'

Type 'null' is not assignable to type 'string'. Angular/TypeScript

Typescript: Type 'null' is not assignable to type error

Typescript Error: setInterval - Type 'Timer' is not assignable to type 'number'

Sequelize Typescript: Type 'FavoriteEntity[]' is not assignable to type 'FavoriteEntity | null'

Type 'string | null' is not assignable to type 'string | undefined error with TypeScript

Typescript, JSON.parse error: "Type 'null' is not assignable to type 'string'."

Using `useContext` with TypeScript - Type 'MyType | null` is not assignable to type 'MyType'

Typescript: is not assignable to type error

Typescript - Type '[][]' is not assignable to type '[]' error

Typescript Type 'string' is not assignable to type

React with TypeScript: Type '{}' is not assignable to type

Typescript: Type 'string' is not assignable to type

Typescript type a is not assignable to type b

Typescript: Type is not assignable to conditional type

Type 'null' is not assignable to type 'XXX'

Type 'null' is not assignable to type 'T'

Type 'null' is not assignable to type 'number'

Type 'null' is not assignable to type 'ValidationErrors'

Typescript type A is not assignable to type A (same type)

HTMLFormElement null is not assignable to parameter of type string | Typescript | EmailJS

Type 'null' is not assignable to type '() => void | null'

Type not assignable (React + Typescript + Firebase)

React typescript is not assignable to parameter of type

React Table Typescript "Type is not assignable"

Typescript, return type not assignable to another

Typescript - string' is not assignable to type 'FC

Typescript/Angular: Object is not Assignable to type