Lee Benson
Lee Benson

Reputation: 11599

Typescript: Are computed object keys actively allowed?

The following compiles fine in Typescript 2.5.3:

interface Test {
  test: string
}

const anything = 'someDifferentKey';

const a: Test = {
  [anything]: true, // no error
  test: 'whatever'
}

But this doesn't:

interface Test {
  test: string
}

const a: Test = {
  someDifferentKey: true, // error
  test: 'whatever'
}

My question is - is it 'safe' to rely on computed object keys always being allowed to tag along with a typed object definition, or are computed properties based on constant vales (e.g. "some"+"differentKey" or the anything const referenced above) simply ignored for now because of a limitation of the current Typescript compiler?

Edit for clarification:

Read the above as: "Does the TS spec give me any guarantee that dynamic properties won't ever cause a compilation error?" per Juan Mendes' comment.

Upvotes: 4

Views: 2576

Answers (1)

Ruan Mendes
Ruan Mendes

Reputation: 92274

The spec does not give you any guarantee that it won't ever check dynamic properties.

As the link above explains, TypeScript only checks the static part of literal objects when checking types, not dynamic [properties]. They are allowed to be on the object but you cannot retrieve it without casting or bracket access.

Your code is almost the same as if you had done

interface Test {
  test: string
}

const anything = 'someDifferentKey';

const a: Test = {
  test: 'whatever'
}

a[anything]: true, // no error because brackets bypass type safety

That is, just because you added a property to the object, it doesn't mean you can retrieve it with type safety.

a.someDifferentKey = false; // ERROR
// You would need
a[anything] = false;

Upvotes: 3

Related Questions