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

Rez Mohsnei

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 ?? '';
David Shortman

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:

// The `current` value is expected to be a `Timer`, and is initialized to `null`
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 'string' is not assignable to type

Typescript, return type not assignable to another

Typescript: is not assignable to type error

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

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

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

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

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

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

Typescript type a is not assignable to type b

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

Type not assignable (React + Typescript + Firebase)

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

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

React typescript is not assignable to parameter of type

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

Typescript - string' is not assignable to type 'FC

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

Typescript: Type 'string' is not assignable to type

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

React Table Typescript "Type is not assignable"

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

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

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

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

Typescript/Angular: Object is not Assignable to type

Typescript: Type is not assignable to conditional type

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

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