TypeScript中如何为解构函数的剩余参数标注类型?
解决TypeScript解构剩余参数的类型标注问题
问题根源
你最初的Params类型定义里,索引签名[key: string]: string要求所有字符串键的属性值必须是string,但boolVar的类型是boolean,直接违反了索引签名的约束,所以触发报错。改成联合类型后,索引签名变成string | boolean,TypeScript无法区分固定属性和剩余属性,只能把rest的类型推断成这个联合类型,不符合你“剩余参数全为string”的需求。
解决方案1:泛型约束(推荐)
通过泛型让参数类型同时满足固定属性和剩余属性的类型要求,TypeScript会自动推断出剩余参数的准确类型:
const foo = <T extends { stringVar: string; boolVar: boolean } & Record<string, string>>( { stringVar, boolVar, ...rest }: T ) => { // rest 的类型为 Omit<T, 'stringVar' | 'boolVar'>,所有值均为 string console.log(rest.name1.toUpperCase()); // 无类型报错 }; foo({ stringVar: 'Test', boolVar: true, name1: 'Deno', name2: 'Doe', });
解决方案2:拆分参数
如果允许调整函数参数结构,可以把固定参数和剩余参数拆成两个独立参数,类型标注更直观:
type FixedParams = { stringVar: string; boolVar: boolean }; type RestParams = Record<string, string>; const foo = (fixed: FixedParams, rest: RestParams) => { // rest 明确为 Record<string, string> 类型 }; foo( { stringVar: 'Test', boolVar: true }, { name1: 'Deno', name2: 'Doe' } );
内容的提问来源于stack exchange,提问作者Deno123
相关产品推荐
相关产品推荐

