我觉得自己做错了。 Typescript试图告诉我做什么?我在这里玩whackamole
TypeScript error in /Users/alex-wilmer/Projects/resideo/pro-portal/packages/web/src/utils/feature-flags/index.tsx(46,9):
Type 'Dispatch<SetStateAction<{ OCT19_DEMO: undefined; }>>' is not assignable to type '() => void'. TS2322
44 | value={{
45 | flags,
> 46 | setFlags,
| ^
47 | }}>
48 | {children}
49 | </FeatureFlagsContext.Provider>
import React, {
createContext,
useContext,
FC,
useState,
Dispatch,
SetStateAction,
} from 'react';
type Flags = {
OCT19_DEMO: string | undefined;
};
type UseFeatureFlagsValue = {
flags: Flags;
setFlags: Dispatch<SetStateAction<{}>>;
};
export const FeatureFlagsContext = createContext({
flags: { OCT19_DEMO: undefined },
setFlags: () => {},
});
export const FEATURE_FLAG_PREFIX = 'REACT_APP_FEATURE_FLAG_';
export const FeatureFlagsProvider: FC<{
children: React.ReactNode;
}> = ({ children }): JSX.Element => {
const [flags, setFlags] = useState(
Object.entries(process.env).reduce(
(acc, [key, val]) => {
if (!key.startsWith(FEATURE_FLAG_PREFIX)) return acc;
acc[key.replace(FEATURE_FLAG_PREFIX, '')] = val;
return acc;
},
{
OCT19_DEMO: undefined,
}
)
);
return (
<FeatureFlagsContext.Provider
value={{
flags,
setFlags,
}}>
{children}
</FeatureFlagsContext.Provider>
);
};
export const useFeatureFlags = (): UseFeatureFlagsValue =>
useContext(FeatureFlagsContext);
答案 0 :(得分:1)
createContext
具有类型参数,因此传入类型UseFeatureFlagsValue
可解决此问题:
export const FeatureFlagsContext = createContext<UseFeatureFlagsValue>({
flags: { OCT19_DEMO: undefined },
setFlags: () => {},
});
您是否需要在此处使用默认值?在大多数情况下,创建上下文时不需要传递默认值(理想情况下,应在可提供有用信息的提供程序中呈现您的使用者)。
defaultValue参数仅在没有组件的情况下使用 树中位于其上方的匹配Provider。这可能对 隔离测试组件而不包装它们。注意:通过 未定义为Provider值不会导致消耗组件 使用defaultValue。
如果不需要使用默认值,则可以使用Non-Null assertion operator使用undefined
创建上下文:
export const FeatureFlagsContext = createContext<UseFeatureFlagsValue>(undefined!);