传递setState作为参数Typescript

时间:2020-07-16 11:08:36

标签: javascript reactjs typescript

请考虑以下内容:

// 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

3 个答案:

答案 0 :(得分:2)

基本上,您要输入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

答案 1 :(得分:0)

您可以为someFunction定义一个非常特定的参数类型,这将为您提供所需的通过/失败次数。

仅允许一个特定对象不是Typescript的真正目的-您应该通过仅允许某些接口来进行保护,而任何具有相同接口的东西都将被允许。

答案 2 :(得分:0)

您可以通过实现回调方法来实现您的目标。

示例:

this.readStudentFile(anyFile, this.callback);

callback(isPass) {
 this.setState({ isPass: isPass });
}

readStudentFile(file: File, callback) {
 if(file) {
   callback(true);
 } else callback(false);
}