在调用外部库函数时选择typescript中的类型



我正在尝试使用一个严格类型的库中的辅助函数,但我似乎无法让它工作。

例如,以下代码来自chakraui.

export interface BaseBreakpointConfig {
sm: string
md: string
lg: string
xl: string
"2xl"?: string
[key: string]: string | undefined
}
export type Breakpoints<T> = T & { base: "0em" }
export const createBreakpoints = <T extends BaseBreakpointConfig>(
config: T,
): Breakpoints<T> => {
warn({
condition: true,
message: [
`[chakra-ui]: createBreakpoints(...) will be deprecated pretty soon`,
`simply pass the breakpoints as an object. Remove the createBreakpoint(..) call`,
].join(""),
})
return { base: "0em", ...config }
}

我想调用createBreakpoints函数而不提供所有的键,我该怎么做?这可能吗?

我尝试使用Pick实用程序,但没有帮助。

type Breakpoints = Pick<BaseBreakpointConfig, 'sm' | 'md' | 'lg'>
const breakpoints = createBreakPoints<Breakpoints>({
sm: "...",
md: "...",
lg: "..."
});

我得到了Property "xl" is missing in type "Breakpoints" but required in type BaseBreakpointConfig错误

使用Partial<Type>返回一个类型,其中Type的每个属性都是可选的,我们可以使T扩展Partial<BaseBreakpointConfig>。这将使createBreakpoints()接受类型为BaseBreakpointConfig子集的参数,如Pick<BaseBreakpointConfig, 'sm' | 'md' | 'lg'>:

export const createBreakpoints = <T extends Partial<BaseBreakpointConfig>>(
config: T,
): Breakpoints<T> => {
// ...
};
const breakpoints = createBreakpoints<Pick<BaseBreakpointConfig, 'sm' | 'md' | 'lg'>>({
sm: "...",
md: "...",
lg: "..."
}); // works

打印稿操场

最新更新