Typescript从默认值推断类型



如何从传递的参数或默认参数推断类型

export type ParamList = {
SignIn: { warningMessage?: string } | undefined
ResetOrCreatePassword: { email: string; hasPasswordAssociated: boolean }
}
type Props = {
text: string
fallbackScreen?: keyof ParamList
params?: ParamList[keyof typeof fallbackScreen] // not valid but shows the goal
}
function MenuLink({fallbackScreen = 'SignIn', params = undefined, ...rest}: Props) {
// impl not important
}
// Cases that should work
MenuLink({ text: "Go to sign in" })
MenuLink({
text: "Reset password",
fallbackScreen: 'ResetOrCreatePassword', 
params: {
email: 'some@email.com',
hasPasswordAssociated: true
}
}) 
// TS should warn about missing params 👇
MenuLink({
text: "Create password",
fallbackScreen: 'ResetOrCreatePassword'
}) 

可以通过使用映射类型来生成可能的道具来实现所需的行为:

type WithParams<T> = {
[K in keyof T]: {
text: string;
fallbackScreen: K;
params: T[K];
}
}[keyof T];
type Props = {
text: string;
fallbackScreen?: never;
params?: never;
} | WithParams<ParamList>;

这会给你这样的东西:

type Props = {
text: string;
fallbackScreen?: never;
params?: never;
} | {
text: string;
fallbackScreen: "SignIn";
params: { warningMessage?: string }
} | { ... }

你可以在下面的操场上看到,它也提供了有用的错误。

游乐场

最新更新