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

问题描述

基于此 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 不是预期类型的​​情况下使用可选参数。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...