PropertyKey in TypeScript

The PropertyKey is a global alias type in TypeScript that can be a string, number, or symbol.

It was to be used as a shorthand way to type property key types.

It's available globally by default, so you just need to use the PropertyKey type in your code.

I've found it particularly useful in situations where I am dynamically updating key/property pairs without explicitly knowing the key name/types beforehand.

Here's an example of how you might use PropertyKey:

const str: string = "test";
const symb: symbol = Symbol();
const num: number = 123;
// We could replace all the previous ones with PropertyKey if we were unsure of their value types. 
const randomKey: PropertyKey = 404;

const obj = {
  [str]: "✅",
  [symb]: "✅",
  [num]: "✅",
  [randomKey]: "✅",
}

Or if we were dynamically creating an object and wanted to have all the keys we could use it with a Record:

type RecordWithAllKeys = Record<
  PropertyKey,
  unknown
>;

Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

TsTypeScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.