构造流类型的函数?
Functions for constructing Flow types?
有什么办法可以做这样的事情吗:
// @flow
function FailureActionType(name: string): Type {
return {type: name, error: string}
}
type SearchFailureAction = FailureActionType("SEARCH_FAILURE")
显然 typing/assignments 在 return 语句中的书写方式存在问题,但它会这样工作
type SearchFailureAction = { type: "SEARCH_FAILURE", error: string }
有什么办法吗?
你想要一个通用的。
type FailureActionType<T: string> = { type: T, error: string }
- 那里的
<T>
说这个类型依赖于另一个类型。
<T: string>
表示这个依赖类型必须是字符串类型。
{ type: T, error: string }
表示结果类型必须具有依赖于对象的 type
键的类型。
您可以通过在 <> 中为 T
传递一个值来使用它,如下所示:
type SearchFailureAction = FailureActionType<"SEARCH_FAILURE">
const action1: SearchFailureAction = { type: 'SEARCH_FAILURE', error: 'some error' }
const action2: SearchFailureAction = { type: 'BAD', error: 'some error' } // type error
泛型非常强大。阅读文档了解更多。
https://flow.org/en/docs/types/generics/
有什么办法可以做这样的事情吗:
// @flow
function FailureActionType(name: string): Type {
return {type: name, error: string}
}
type SearchFailureAction = FailureActionType("SEARCH_FAILURE")
显然 typing/assignments 在 return 语句中的书写方式存在问题,但它会这样工作
type SearchFailureAction = { type: "SEARCH_FAILURE", error: string }
有什么办法吗?
你想要一个通用的。
type FailureActionType<T: string> = { type: T, error: string }
- 那里的
<T>
说这个类型依赖于另一个类型。 <T: string>
表示这个依赖类型必须是字符串类型。{ type: T, error: string }
表示结果类型必须具有依赖于对象的type
键的类型。
您可以通过在 <> 中为 T
传递一个值来使用它,如下所示:
type SearchFailureAction = FailureActionType<"SEARCH_FAILURE">
const action1: SearchFailureAction = { type: 'SEARCH_FAILURE', error: 'some error' }
const action2: SearchFailureAction = { type: 'BAD', error: 'some error' } // type error
泛型非常强大。阅读文档了解更多。 https://flow.org/en/docs/types/generics/