微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使函数的第二个参数的类型取决于第一个参数的值和映射中的条目

如何解决如何使函数的第二个参数的类型取决于第一个参数的值和映射中的条目

基于此 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?