如何解决如何使函数的第二个参数的类型取决于第一个参数的值和映射中的条目
基于此 stackoverflow 帖子:TypeScript: How to make an optional second argument required based on the value of the first argument,我正在尝试实现一个功能
hasRight(right: string,options: SomeOptionsBasedOnTheName) => boolean
其中权利的名称来自静态对象,例如:
const rightList = {
'a': {},'b': {
rule: (options: {otherUserId: UserIdType}) => boolean
},'c': {
rule: (options: {accessingObjectId: ObjectIdType,accessMethod: MethodType}) => boolean
}
}
type RightMatrix = typeof rightList;
我希望 hasRight
的第二个参数与给定权限的 rule
的第一个参数相同。
要访问具有给定索引的函数参数,我已经构建了
type Arg<
FN extends (...args: any[]) => any,ArgNum extends number
> = Parameters<FN>[ArgNum];
//usage:
type FirstParameter = Arg<(options: MyOptionsType,second: any) => boolean,0>
// = MyOptionsType
type ConditionalOptions<T,K extends keyof T> = T[K] extends null? [] : T[K];
export const hasRight = <R extends keyof RightMatrix>(
right: R,options: ConditionalOptions<RightMatrix,R>,) => boolean
但是,我在获取 Arg<FN,Index>
类型的“规则”时遇到问题
解决方法
以下应该或多或少起作用。
type UserIdType = 'userIdType';
type ObjectIdType = 'objectIdType';
type MethodType = 'methodType';
const rightList = {
'a': {},'b': {
rule: (options: {otherUserId: UserIdType}) => true,},'c': {
rule: (options: {accessingObjectId: ObjectIdType,accessMethod: MethodType}) => false,'d': {
rule: 'hello'
}
}
type RightMatrix = typeof rightList;
type ConditionalOptions<T> = T extends { rule: (options: infer R) => boolean } ? R : null;
declare function hasRight<K extends keyof RightMatrix>(right: K,...options: ConditionalOptions<RightMatrix[K]> extends never ? [undefined?] : [ConditionalOptions<RightMatrix[K]>]): boolean;
hasRight('a');
hasRight('b',{ otherUserId: 'userIdType' });
hasRight('c',{ accessingObjectId: 'objectIdType',accessMethod: 'methodType' });
hasRight('d');
您可以将 ConditionalOptions
修改为
type ConditionalOptions<T> = T extends { rule: (options: infer R,...args: any[]) => boolean } ? R : null;
接受带有多个参数的 rule
函数:
rule: (options: {accessingObjectId: ObjectIdType,accessMethod: MethodType},additionalParam: string) => false,
更新:更新以允许在 rule
不是预期类型的情况下使用可选参数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。