我有一个带有类型保护和函数剩余参数的 Typescript 示例:
interface BaseProps {
username: string;
password: string;
}
type Props = BaseProps & (
| {isAdmin: true, adminName: string}
| {isAdmin: false}
)
// Doesn't works
const myFn = ({isAdmin, ...rest}: Props) => {
if(isAdmin === true) {
rest.adminName; // Property 'adminName' does not exist on type '{ username: string; adminName: string; } | { username: string; }'.
}
}
// It works
const myFn2 = (args: Props) => {
if(args.isAdmin === true) {
args.adminName;
}
}
其余参数和类型保护有什么问题?
更新解决方案:
我找到了解决方案,Assert Functions
用于解决问题。
declare function assertType<T>(val: unknown): asserts val is T;
const myFn = ({password, isAdmin, ...rest}: Props) => {
if(isAdmin === true) {
assertType<Omit<Props & {isAdmin: true}, keyof Props>>(rest);
rest.adminName; // <=== HERE
rest.username;
// Should be error
rest.password;
}
}