【发布时间】:2026-02-26 12:45:01
【问题描述】:
我正试图将我的头包裹在 Flow 周围。
这按预期工作:
// @flow
type FontName = string
const doSomethingWithFontName = (fontName: FontName) => console.log(fontName)
type StrictFontName = 'Arial' | 'Verdana' | 'Times'
const doSomethingWithStrictFontName = (fontName: StrictFontName) => doSomethingWithFontName(fontName)
doSomethingWithStrictFontName('Times')
从doSomethingWithStrictFontName 调用doSomethingWithFontName 工作正常。我猜 Flow 看到我的枚举 StrictFontName 只包含字符串,因此我可以使用字符串或 StrictFontName 调用 doSomethingWithFontName
但是将变量包装在对象中失败:
// @flow
type Typography = {
fontName?: string;
}
const doSomethingWithTypography = (typography: Typography) => console.log(typography)
type StrictTypography = Typography & {
fontName?: 'Arial' | 'Verdana' | 'Times';
}
const doSomethingWithStrictTypography = (typography: StrictTypography) => {
doSomethingWithTypography(typography)
}
doSomethingWithStrictTypography({fontName: 'Times'})
我只是在这里将我们的严格对象转发给一个更松散的函数,为什么这不起作用? Flow 可以告诉StrictTypography 的fontName 仍然是一个字符串对吧?
我已阅读此thread 并想出了将超类型作为接口作为解决方法:
// @flow
// Interface instead of type
interface Styles {
fontName?: string;
}
const doSomethingWithStyling = (styles: Styles) => console.log(styles)
type StrictStyles = Styles & {
fontName?: 'Arial' | 'Verdana' | 'Times';
}
const doSomethingWithStrictStyling = (styles: StrictStyles) => {
doSomethingWithStyling(styles)
}
doSomethingWithStrictStyling({fontName: 'Times'})
这似乎可行,但我不确定这是否是正确的方法。另外,如果我导入这个接口,我会得到一个Use of future reserved word in strict mode...
你可以找到游乐场here
【问题讨论】:
标签: flowtype