What is the square bracketed field in the interface in TypeScript

Viewed 164
export interface Principal {
  name: string; // just a field
  [attribute: string]: any; // allowed custom fields

  [securityId]: string; // what does this mean ?
}

What does securityId mean ?

2 Answers

securityId is a computed property name.

To make this code compile, securityId must be a value with type constrained to a literal string, or a unique symbol type.

For example:

const securityId: "security" = "security";

interface Principal {
    [securityId]: string;
}

specifies a property named security.

If securityId doesn't have a literal type, this will be an error:

const securityId: string = "security";

interface Principal {
    // ERROR: A computed property name in an interface must refer to an
    // expression whose type is a literal type or a 'unique symbol' type.
    [securityId]: string;
}

Note: I've tried to find references to this behavior in the specification but it appears out of date and not a priority - edits welcome!

securityId is called a constant-named property on a type, introduced in TypeScript v2.7:

const securityId = Symbol() // create symbol value

export interface Principal {
  [securityId]: string; // .. and use it as property name in the *type system*
}

You can also use a number or string instead of Symbol - be aware, that all need to be const variables:

// works
const securityId = 3 // number literal type
const securityId = "foo" // string literal type

// doesn't work
let securityId = "foo" // let
const securityId: string = "foo" // wide string

Constant-named properties are the equivalent of computed property names in the type system and especially useful in combination with well-known symbols or unique user properties like with branded types.

Here is a code example on the Playground.

Related