0

I defined a service type and my purpose is to create a function with two params.

  • first one is service type which is key of type Service
  • second one is a string array of the attribute keys per the first argument.

something like below

type MyService = {
  service1: { x: string, y: number },
  service2: { m: string, n: number },
};

function useService(ns: keyof MyService, serviceNames: Array<keyof MyService[typeof ns extends keyof MyService ? typeof ns : never]>): void {
  console.log(serviceNames);
}

useService('service1', ['x', 'y']);  // now the second parameter type is always never

I don't know whether ts could check the runtime type? Please advice.

Shankar Ganesh Jayaraman
  • 1,401
  • 1
  • 16
  • 22

3 Answers3

0

No Typescript cant check this at runtime sadly...

This question might be useful to you

Ulrich Stark
  • 401
  • 3
  • 12
0

Typescript code when it gets compiled, the resultant JS code never has types. So it cannot check at runtime.

"use strict";
function useService(ns, serviceNames) {
    console.log(serviceNames);
}
useService('service1', ['x', 'y']);
Shivam Pandey
  • 3,756
  • 2
  • 19
  • 26
0

I think this is the solution you might want to.

use generic to get type from argments.

type MyService = {
  service1: { x: string, y: number },
  service2: { m: string, n: number },
};

function useService<T extends keyof MyService>(ns: T, serviceNames: Array<keyof MyService[T]>): void {
  console.log(serviceNames);
}

useService('service1', ['x', 'y']); // it'll remove the error
bjKim
  • 63
  • 1
  • 5