TypeScript 2.1: keyof and Lookup Types

  • Equipped with keyof , we can now improve the type annotations of our prop function.
  • It queries the set of keys for a given type, which is why it’s also called an index type query .
  • function prop(obj: T, key: K) { return obj[key]; }
  • There are plenty of square brackets involved in the return type but there’s the type safety we’ve been looking for!
  • With these two type annotations in place, obj must be an object and key must be a string.

TypeScript 2.1 introduces the keyof operator and lookup types, which help capture even more of JavaScript’s dynamic nature in a static type system.

@SGoresht: @TypeScript 2.1: keyof and Lookup Types – #webdevelopment #Angularjs

function, for instance:

looks like.

So how could we type this function in TypeScript? Here’s a first attempt:

, however:

function. We need to provide a little more type information to make that possible.

interface:

type to get back a type representing all its property keys, which is a union of string literal types:

type rather than a generic one.

parameter. Instead, we’ll require that the key actually exists on the type of the object that is passed in:

method, each one will have the correct type:

object?

The compiler complains, and that’s a good thing! It prevented us from trying to read a property that’s not there.

method is typed in the lib.es2017.object.d.ts type declaration file that ships with the TypeScript compiler:

method returns an array of tuples, each containing a property key and the corresponding value. There are plenty of square brackets involved in the return type, admittedly, but there’s the type safety we’ve been looking for!

TypeScript 2.1: keyof and Lookup Types