Home > Mobile >  Typescript interface with unknown number of generic properties which all should be typed as booleans
Typescript interface with unknown number of generic properties which all should be typed as booleans

Time:09-22

I want to make a typescript interface with unknown number of generic properties which all should be typed as booleans. If I wanted to make an interface with property 'foo' and a generic value I would do:

export interface Foo<T> {
  foo: T;
}

Since I want to do basically the opposite I tried

export interface booleansMap<T> {
  T: boolean;
}

but I got

'T' is defined but never used.(@typescript-eslint/no-unused-vars)

from eslint

Having trouble finding this in the docs (probably not googling with the correct nomenclature) - so I was wondering if anyone understands and can explain how to make such an interface

It should be able to handle something like:

{
  foo: false,
  bar: true,
  baz: false
}

or

{
  foo: true,
}

or any other object with any number of properties as long as all of the values will be booleans...

CodePudding user response:

You don't need generics for this. You can just use [K: string] to specify a general key:

type booleanMap = { [K: string]: boolean }

with interface definition:

interface booleansMap {
  [K: string]: boolean;
}

Or alternatively use Record:

type booleanMap = Record<string, boolean>

Playground

  • Related