Home > Mobile >  How to use symbols as a keyof type
How to use symbols as a keyof type

Time:03-31

Consider this:

type Foo = keyof Set<string>

Here, Foo represents the type of all keys in the Set object, e.g. add or delete:

const a: Foo = 'add'; ✅

However, Set also has some well-known symbol properties:

const b: Foo = Symbol.iterator; ✅

However, in a Pick type, how can I reference a symbol key?

type A = Pick<Set<string>, 'add'> ✅
type B = Pick<Set<string>, Symbol.iterator> ❌

The second Pick does not work - "Symbol only refers to a type but is being used as a namespace here."

CodePudding user response:

Symbol.iterator is a value, and you want the type.

type B = Pick<Set<string>, typeof Symbol.iterator>

seems to do the trick.

CodePudding user response:

You can use typeof Symbol.iterator instead:

type pickedIterator = Pick<Set<string>, typeof Symbol.iterator> 
// { [Symbol.iterator]: () => IterableIterator<string> }

TypeScript playground

  • Related