user5047085
user5047085

Reputation:

Difference between `type {}` and `Dictionary<T> { [key: string]: T; }`

The async library uses this declaration

export interface Dictionary<T> { [key: string]: T; }

but I am confused, how is this different from

type {}

?

Perhaps type {} allows for Symbol to be used for keys, and the Dictionary interface only allows for keys to be strings?

Here are the typings for async: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/async/index.d.ts#L9

Upvotes: 1

Views: 841

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170805

There is a big and obvious difference in addition to John Weisz's answer: Dictionary<T> allows you to specify T, {} doesn't.

Upvotes: 0

John Weisz
John Weisz

Reputation: 31972

When using --noImplicitAny, the index-signature in the Dictionary<T> interface above will allow arbitrary string-based property access, while {} will not, because it does not have an index-signature:

interface Dictionary<T> { [key: string]: T; }

let a: Dictionary<string> = {};
let b: {} = {};

a["one"] = "two"; // OK
b["two"] = "three"; // Not OK

This is not a problem when --noImplicitAny is not used, or --suppressImplicitAnyIndexErrors is used, because then every object type is treated as having an implicit "any-to-any" index-signature by default.

Upvotes: 2

Related Questions