2

I want to define some type which is key of some other type. It is possible to do this

interface B {
   x: something;
   y: string;
   z: something;
}

type keyOfB = keyof B;

export class A {
    foo: keyOfB;
}

But at same time i want to foo be only some type eg string or something, how to combine it?

foo: keyOfB & type 

doesnt work.

Theoretically it is job for Pick<> or Extract<> but i cant make it working

https://www.typescriptlang.org/docs/handbook/utility-types.html

luky
  • 2,263
  • 3
  • 22
  • 40

1 Answers1

0

So i modified the answer posted here https://stackoverflow.com/a/53899815

to this and it seems to work :)

type KeyOfType<T extends object, Type> = Exclude<{
    [K in keyof T]: T[K] extends Type
      ? K
      : never
  }[keyof T], undefined>

usage:

interface B {
   x: something;
   y: string;
   z: something;
}

export class A {
    foo: KeyOfType<B, string>;
}

Foo prop will be only allowed to assign key of B that are type of string. (only 'y' in this case)

luky
  • 2,263
  • 3
  • 22
  • 40