1

I have interface and object which represents this interface:

MyInterface {
  variableOne: string;
  variableTwo: boolean;
  variableThree: boolean; 
  ...
}

Also I have function toggleFunction(x) which gets a key and toggles it in my object. Which type do I need to set in param x in my toggle function to use it for toggle all boolean key in my object?

For example I need something like: toggleFunction(x: TYPE?)

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Ilia Ch.
  • 45
  • 1
  • 8
  • Possible duplicate of [How to write PickByValue type?](https://stackoverflow.com/questions/55150760/how-to-write-pickbyvalue-type) – jcalz Nov 05 '19 at 18:58

2 Answers2

2

Use keyof.

function toggleFunction(x: keyof MyInterface): void {
    // ...
}
kaya3
  • 47,440
  • 4
  • 68
  • 97
2

You can use a conditional mapped type that I usually call KeysMatching:

type KeysMatching<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];

And then toggleFunction() can be defined like this:

declare const o: MyInterface; // or wherever it comes from
function toggleFunction(x: KeysMatching<MyInterface, boolean>) {
    o[x] = !o[x];
}

toggleFunction("variableTwo"); // okay
toggleFunction("variableThree"); // okay
toggleFunction("variableOne"); // error!

Hope that helps; good luck!

Link to code

jcalz
  • 264,269
  • 27
  • 359
  • 360
  • Could you please explain a little the last part of your code: ```[keyof T]``` For what it is? – Ilia Ch. Nov 05 '19 at 20:31
  • It's a [lookup type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types). If you have an object type `T` and a key (or union of keys) of that object type `K`, then `T[K]` is the type of the property at that key (or the union of properties at those keys). For example, `{a: string, b: number, c: boolean}["a" | "b"]` is `string | number`. – jcalz Nov 06 '19 at 00:17