Typescipt string literals as generics with dependent type: Exhausiveness check in switch

29 Views Asked by At

As a follow up of this question

I have the following code snippet:

const operations = {
   DDB: ["getItem"] as const;
   S3: ["putObject"] as const;
}
type service = keyof typeof operations;
type serviceOperation<T extends service> = typeof operation[T][number]
type resourceFor<T extends service> = T extends 'S3' ? Bucket : T extends 'DDB' : Table : never;

const setPermission = <T extends service>(serviceType: T, operation: serviceOperation<T>): ((caller: LambdaFunction, resource: ResourceFor<T>) => void) => {
  switch(serviceType) {
    case 'DDB':
        switch(operation) {
            case 'getItem': return (lambda: LambdaFunction, table: Table) => table.grandReadData(lambda);
        }
    case 'S3':
        switch(operation) {
            case 'putObject': return (lambda: LambdaFunction, bucket: Bucket) => bucket.grandWrite(lambda);
        }
  }
};

This has 2 issues:

  1. I need to cast the return statements to the as ((caller: LambdaFunction, resource: ResourceFor<T>) => void). It is not nice, but I can live with that.
  2. with the casts, it fails with Function lacks ending return statement and return type does not include 'undefined'.

The suggestion in the original question does not solve this case unfortunately

0

There are 0 best solutions below