gpt4 book ai didi

javascript - 将 setState 作为参数传递 Typescript

转载 作者:行者123 更新时间:2023-12-03 08:40:18 26 4
gpt4 key购买 nike

考虑以下因素:

// external file

export const someFunction = setState => {
setState({ value: "some new string" })
}

// component's file

import { someFunction } from "pathToFile"

interface TState {
value: string
}

const [state, setState] = useState<TState>({ value: "some string" })

useEffect(() => {
someFunction(setState)
}, [])

是否可以实现 someFunction仅接受此特定 setState 函数作为参数?如果可以的话,该怎么做?

明确地说,我想要:

someFunction(setState) // pass
someFunction(setAnotherState) // fail
someFunction(anotherFunctions) // fail
someFunction() // fail
someFunction(0) // fail
someFunction(true) // fail
someFunction({}) // fail

最佳答案

基本上,您要求的是 nominal type :

type NominalSetState = React.Dispatch<React.SetStateAction<TState>> &
{ readonly __brand_setState__: unique symbol }

const someFunction = (setState: NominalSetState) => {
setState({ value: "some new string" })
}

function useNominalState(init: TState) {
return useState<TState>(init) as [TState, NominalSetState]
}

const [state, setState] = useNominalState({ value: "some string" })
const [anotherState, setAnotherState] = useState<TState>({ value: "some string" })
现在,测试的行为符合预期:
someFunction(setState) // pass
someFunction(setAnotherState) // fail
someFunction() // fail
someFunction(0) // fail
someFunction(true) // fail
someFunction({}) // fail
someFunction((...arg: any[]) => any) // fail

Live code example

关于javascript - 将 setState 作为参数传递 Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62933379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com