Support number and symbol named properties with keyof and mapped types

TypeScript 2.9 adds support for number and symbol named properties in index types and mapped types.Previously, the keyof operator and mapped types only supported string named properties.

Changes include:

  • An index type keyof T for some type T is a subtype of string | number | symbol.
  • A mapped type { [P in K]: XXX } permits any K assignable to string | number | symbol.
  • In a for…in statement for an object of a generic type T, the inferred type of the iteration variable was previously keyof T but is now Extract<keyof T, string>. (In other words, the subset of keyof T that includes only string-like values.)

Given an object type X, keyof X is resolved as follows:

  • If X contains a string index signature, keyof X is a union of string, number, and the literal types representing symbol-like properties, otherwise
  • If X contains a numeric index signature, keyof X is a union of number and the literal types representing string-like and symbol-like properties, otherwise
  • keyof X is a union of the literal types representing string-like, number-like, and symbol-like properties.

Where:

  • String-like properties of an object type are those declared using an identifier, a string literal, or a computed property name of a string literal type.
  • Number-like properties of an object type are those declared using a numeric literal or computed property name of a numeric literal type.
  • Symbol-like properties of an object type are those declared using a computed property name of a unique symbol type.

In a mapped type { [P in K]: XXX }, each string literal type in K introduces a property with a string name, each numeric literal type in K introduces a property with a numeric name, and each unique symbol type in K introduces a property with a unique symbol name.Furthermore, if K includes type string, a string index signature is introduced, and if K includes type number, a numeric index signature is introduced.

Example
  1. const c = "c";
  2. const d = 10;
  3. const e = Symbol();
  4. const enum E1 { A, B, C }
  5. const enum E2 { A = "A", B = "B", C = "C" }
  6. type Foo = {
  7. a: string; // String-like name
  8. 5: string; // Number-like name
  9. [c]: string; // String-like name
  10. [d]: string; // Number-like name
  11. [e]: string; // Symbol-like name
  12. [E1.A]: string; // Number-like name
  13. [E2.A]: string; // String-like name
  14. }
  15. type K1 = keyof Foo; // "a" | 5 | "c" | 10 | typeof e | E1.A | E2.A
  16. type K2 = Extract<keyof Foo, string>; // "a" | "c" | E2.A
  17. type K3 = Extract<keyof Foo, number>; // 5 | 10 | E1.A
  18. type K4 = Extract<keyof Foo, symbol>; // typeof e

Since keyof now reflects the presence of a numeric index signature by including type number in the key type, mapped types such as Partial<T> and Readonly<T> work correctly when applied to object types with numeric index signatures:

  1. type Arrayish<T> = {
  2. length: number;
  3. [x: number]: T;
  4. }
  5. type ReadonlyArrayish<T> = Readonly<Arrayish<T>>;
  6. declare const map: ReadonlyArrayish<string>;
  7. let n = map.length;
  8. let x = map[123]; // Previously of type any (or an error with --noImplicitAny)

Furthermore, with the keyof operator’s support for number and symbol named keys, it is now possible to abstract over access to properties of objects that are indexed by numeric literals (such as numeric enum types) and unique symbols.

  1. const enum Enum { A, B, C }
  2. const enumToStringMap = {
  3. [Enum.A]: "Name A",
  4. [Enum.B]: "Name B",
  5. [Enum.C]: "Name C"
  6. }
  7. const sym1 = Symbol();
  8. const sym2 = Symbol();
  9. const sym3 = Symbol();
  10. const symbolToNumberMap = {
  11. [sym1]: 1,
  12. [sym2]: 2,
  13. [sym3]: 3
  14. };
  15. type KE = keyof typeof enumToStringMap; // Enum (i.e. Enum.A | Enum.B | Enum.C)
  16. type KS = keyof typeof symbolToNumberMap; // typeof sym1 | typeof sym2 | typeof sym3
  17. function getValue<T, K extends keyof T>(obj: T, key: K): T[K] {
  18. return obj[key];
  19. }
  20. let x1 = getValue(enumToStringMap, Enum.C); // Returns "Name C"
  21. let x2 = getValue(symbolToNumberMap, sym3); // Returns 3

This is a breaking change; previously, the keyof operator and mapped types only supported string named properties.Code that assumed values typed with keyof T were always strings, will now be flagged as error.

Example
  1. function useKey<T, K extends keyof T>(o: T, k: K) {
  2. var name: string = k; // Error: keyof T is not assignable to string
  3. }

Recommendations

  • If your functions are only able to handle string named property keys, use Extract<keyof T, string> in the declaration:
  1. function useKey<T, K extends Extract<keyof T, string>>(o: T, k: K) {
  2. var name: string = k; // OK
  3. }
  • If your functions are open to handling all property keys, then the changes should be done down-stream:
  1. function useKey<T, K extends keyof T>(o: T, k: K) {
  2. var name: string | number | symbol = k;
  3. }
  • Otherwise use —keyofStringsOnly compiler option to disable the new behavior.

Generic type arguments in JSX elements

JSX elements now allow passing type arguments to generic components.

Example
  1. class GenericComponent<P> extends React.Component<P> {
  2. internalProp: P;
  3. }
  4. type Props = { a: number; b: string; };
  5. const x = <GenericComponent<Props> a={10} b="hi"/>; // OK
  6. const y = <GenericComponent<Props> a={10} b={20} />; // Error

Generic type arguments in generic tagged templates

Tagged templates are a form of invocation introduced in ECMAScript 2015.Like call expressions, generic functions may be used in a tagged template and TypeScript will infer the type arguments utilized.

TypeScript 2.9 allows passing generic type arguments to tagged template strings.

Example
  1. declare function styledComponent<Props>(strs: TemplateStringsArray): Component<Props>;
  2. interface MyProps {
  3. name: string;
  4. age: number;
  5. }
  6. styledComponent<MyProps> `
  7. font-size: 1.5em;
  8. text-align: center;
  9. color: palevioletred;
  10. `;
  11. declare function tag<T>(strs: TemplateStringsArray, ...args: T[]): T;
  12. // inference fails because 'number' and 'string' are both candidates that conflict
  13. let a = tag<string | number> `${100} ${"hello"}`;

import types

Modules can import types declared in other modules. But non-module global scripts cannot access types declared in modules. Enter import types.

Using import("mod") in a type annotation allows for reaching in a module and accessing its exported declaration without importing it.

Example

Given a declaration of a class Pet in a module file:

  1. // module.d.ts
  2. export declare class Pet {
  3. name: string;
  4. }

Can be used in a non-module file global-script.ts:

  1. // global-script.ts
  2. function adopt(p: import("./module").Pet) {
  3. console.log(`Adopting ${p.name}...`);
  4. }

This also works in JSDoc comments to refer to types from other modules in .js:

  1. // a.js
  2. /**
  3. * @param p { import("./module").Pet }
  4. */
  5. function walk(p) {
  6. console.log(`Walking ${p.name}...`);
  7. }

Relaxing declaration emit visiblity rules

With import types available, many of the visibility errors reported during declaration file generation can be handled by the compiler without the need to change the input.

For instance:

  1. import { createHash } from "crypto";
  2. export const hash = createHash("sha256");
  3. // ^^^^
  4. // Exported variable 'hash' has or is using name 'Hash' from external module "crypto" but cannot be named.

With TypeScript 2.9, no errors are reported, and now the generated file looks like:

  1. export declare const hash: import("crypto").Hash;

Support for import.meta

TypeScript 2.9 introduces support for import.meta, a new meta-property as described by the current TC39 proposal.

The type of import.meta is the global ImportMeta type which is defined in lib.es5.d.ts.This interface is extremely limited.Adding well-known properties for Node or browsers requires interface merging and possibly a global augmentation depending on the context.

Example

Assuming that __dirname is always available on import.meta, the declaration would be done through reopening ImportMeta interface:

  1. // node.d.ts
  2. interface ImportMeta {
  3. __dirname: string;
  4. }

And usage would be:

  1. import.meta.__dirname // Has type 'string'

import.meta is only allowed when targeting ESNext modules and ECMAScript targets.

New —resolveJsonModule

Often in Node.js applications a .json is needed. With TypeScript 2.9, —resolveJsonModule allows for importing, extracting types from and generating .json files.

Example
  1. // settings.json
  2. {
  3. "repo": "TypeScript",
  4. "dry": false,
  5. "debug": false
  6. }
  1. // a.ts
  2. import settings from "./settings.json";
  3. settings.debug === true; // OK
  4. settings.dry === 2; // Error: Operator '===' cannot be applied boolean and number
  1. // tsconfig.json
  2. {
  3. "compilerOptions": {
  4. "module": "commonjs",
  5. "resolveJsonModule": true,
  6. "esModuleInterop": true
  7. }
  8. }

—pretty output by default

Starting TypeScript 2.9 errors are displayed under —pretty by default if the output device is applicable for colorful text.TypeScript will check if the output steam has isTty property set.

Use —pretty false on the command line or set "pretty": false in your tsconfig.json to disable —pretty output.

New —declarationMap

Enabling —declarationMap alongside —declaration causes the compiler to emit .d.ts.map files alongside the output .d.ts files.Language Services can also now understand these map files, and uses them to map declaration-file based definition locations to their original source, when available.

In other words, hitting go-to-definition on a declaration from a .d.ts file generated with —declarationMap will take you to the source file (.ts) location where that declaration was defined, and not to the .d.ts.