为什么 Typescript 无法识别我为“useState”状态变量提供的类型?
Why is Typescript not recognizing the type I'm giving to my `useState` state variables?
为什么会出现下面的代码:
import React, {Dispatch, SetStateAction, useState} from 'react'
type Fn = () => void
export const Component = () => {
const [fn, setFn]: [Fn, Dispatch<SetStateAction<Fn>>] = useState(() => {})
return <p>{`${typeof fn}, ${typeof setFn}`}</p>
}
产生以下 Typescript 错误:
Type '[void, Dispatch<SetStateAction>]' is not assignable to type '[Fn, Dispatch<SetStateAction>]'.
Type at position 0 in source is not compatible with type at position 0 in target.
Type 'void' is not assignable to type 'Fn'.ts(2322)
const fn: Fn
?
你可以亲眼看到这个效果here
我的看法:
- 我给
useState
一个默认值 () => {}
,类型为 () => void
。
- 我正在声明一个
fn
类型 Fn
又名 () => void
的常量
- 这些类型完全相同,不是
void
那么为什么 Typescript 指的是 Type '[void, Dispatch<SetStateAction>]
'?
它从哪里得到那个类型?
我创建的唯一类型 (afaik) 是 Type '[Fn, Dispatch<SetStateAction<Fn>>]'
,还是我做错了什么?
作为后续问题:是否有更简洁的方式来严格输入此类内容?
如果删除类型注释,您会看到 fn
的类型被推断为 void
:
发生这种情况是因为,如果将函数传递给 useState
,this is taken as a callback that React runs to determine the initial state。这是一种不调用确定每个渲染的初始状态的昂贵进程的方法。
如果你想让状态成为一个函数,你需要将它嵌套在另一个函数中。
const [fn, setFn] = useState(() => () => {})
无需明确注明类型 - TypeScript 可以自动推断。
为什么会出现下面的代码:
import React, {Dispatch, SetStateAction, useState} from 'react'
type Fn = () => void
export const Component = () => {
const [fn, setFn]: [Fn, Dispatch<SetStateAction<Fn>>] = useState(() => {})
return <p>{`${typeof fn}, ${typeof setFn}`}</p>
}
产生以下 Typescript 错误:
Type '[void, Dispatch<SetStateAction>]' is not assignable to type '[Fn, Dispatch<SetStateAction>]'.
Type at position 0 in source is not compatible with type at position 0 in target.
Type 'void' is not assignable to type 'Fn'.ts(2322)
const fn: Fn
?
你可以亲眼看到这个效果here
我的看法:
- 我给
useState
一个默认值() => {}
,类型为() => void
。 - 我正在声明一个
fn
类型Fn
又名() => void
的常量
- 这些类型完全相同,不是
void
那么为什么 Typescript 指的是 Type '[void, Dispatch<SetStateAction>]
'?
它从哪里得到那个类型?
我创建的唯一类型 (afaik) 是 Type '[Fn, Dispatch<SetStateAction<Fn>>]'
,还是我做错了什么?
作为后续问题:是否有更简洁的方式来严格输入此类内容?
如果删除类型注释,您会看到 fn
的类型被推断为 void
:
发生这种情况是因为,如果将函数传递给 useState
,this is taken as a callback that React runs to determine the initial state。这是一种不调用确定每个渲染的初始状态的昂贵进程的方法。
如果你想让状态成为一个函数,你需要将它嵌套在另一个函数中。
const [fn, setFn] = useState(() => () => {})
无需明确注明类型 - TypeScript 可以自动推断。