Questions tagged [index-signature]

Use for questions on index signatures, a feature of TypeScript that allows for object types with unknown properties (both numeric and string signatures are supported) to be restricted to certain types. Always use with the [typescript] language tag. Do not use it for questions that merely involve index signatures.

About

Index Signatures allow object types in TypeScript to have unknown properties that are restricted to certain types. Signatures can be either numeric or string-based, and both can be present at the same time (with a small caveat). The presence of an index signature also restricts known properties to be of the same type unless they are extracted in another object type and combined with the index signature via a union type.

type StringIndexed = { [key:string]: boolean; };
const validSI: StringIndexed = { isStringBased: true }; // Ok
const invalidSI: StringIndexed = { answer: 42 }; // Type 'number' is not assignable to type 'boolean'

type NumberIndexed = { [index:number]: string; };
const validNI: NumberIndexed = ["one", "two"];
const invalidNI: NumberIndexed = [1,2]; // Type 'number' is not assignable to type 'string'

type BothIndexed = {
    [key:string]: boolean|string; // Needs to be a union because A[0] is the same as A["0"]
    [index:number]: string;
};
const validBoth:BothIndexed = {
    acceptsBoth: true, // Ok
    thisIsAlsoOkThough: "anything", // a trade-off for combining signatures
    42: "answer" // Ok
}

type WithKnownProperties = {
    [prop: string]: string;
} | { answer: 42; };
const known: WithKnownProperties = {
    answer: 42, // Ok
    question: "unknown" // Ok
}

Usage Guidance

Use for questions about index signatures, their usage rules and caveats, not for questions simply involving them.

Always use with the language tag.

67 questions
47
votes
2 answers

Difference between index signature and Record for empty object?

I cannot figure out the difference between index signatures and record types. Could someone explain the differences and when to use one versus the other? Specifically, I am looking to define the type of an object that will have random strings for…
mkusps
  • 520
  • 1
  • 4
  • 7
26
votes
1 answer

How do I add an index signature for a mapped type?

Suppose I have interface interface X { a: string; b: number; c: boolean; } and a function function values(x: X) { return Object.keys(x).map(s => x[s]) } When I enable typescript's strict flag I get the error "Element implicitly has an…
Stuart
  • 307
  • 4
  • 9
19
votes
1 answer

What does a TypeScript index signature actually mean?

I've been writing TypeScript for a while and am confused about what an index signature means. For example, this code is legal: function fn(obj: { [x: string]: number }) { let n: number = obj.something; } But this code, which does basically the…
Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
10
votes
5 answers

How to add index signature in TypeScript

I am trying to use reduce with Typescript to reach a total count of incoming messages. I'm confused on how to add an index signature. I keep getting the error: " Element implicitly has an 'any' type because type '{}' has no index signature." on…
Bethany
  • 1,003
  • 5
  • 12
  • 18
9
votes
2 answers

How to mix index signature with known properties?

Let's say the interface has some known properties with their types, and can have additional ones with unknown keys and some other types, something like: interface Foo { length: number; [key: string]: string; } const foo : Foo = { length: 1, …
mbehzad
  • 3,758
  • 3
  • 22
  • 29
8
votes
4 answers

How to combine known interface properties with a custom index signature?

How do you type an object that can have both a few declared optional properties, e.g.: { hello?: string, moo?: boolean } as well as custom properties (that must be functions), e.g.: [custom: string]: (v?: any) => boolean This is…
papercowboy
  • 3,369
  • 2
  • 28
  • 32
6
votes
1 answer

How to create a TypeScript interface with both an index signature and a fixed property of a different type?

From a legacy api I am getting a JSON response like so: const someObject = { "general": { "2000": 50, "4000": 100, "8000": 200, }, "foo": [ 0, 1, 2, ], "bar": [ 5, …
k0pernikus
  • 60,309
  • 67
  • 216
  • 347
4
votes
1 answer

How to match value types to keys when using index signatures in TypeScript?

I have a code in a library for doing some kind of eventsourcing. It defines events with a given type and data for each kind of events. I want to write a reduce function that walks through a list of events and apply them to a given initial value. My…
lencse
  • 225
  • 1
  • 6
4
votes
1 answer

Typescript: how can I exclude methods from the index signature of classes?

I have a class that can be extended by the user like this: class Foo { extendFoo(key: string, value: string) { this[key] = value; //<==typescript error: missing index signature } } as you can see, this can be extended with strings.…
niryo
  • 1,275
  • 4
  • 15
  • 26
4
votes
1 answer

Typescript Index Signature and methods in the implementing class doesn't work

I`m trying to create my own Typescript dictionary like class, but with some custom methods to use in my code. I can create the basic dictionary like this: export interface IDictionary { [property: string]: T; }; export class Dictionary
Wayne Barnard
  • 164
  • 1
  • 8
3
votes
1 answer

Using JSDoc to set an index signature on an ES6 Class

In Typescript, you'd just do this: class Test { [key: string]: whatever } Which allows you to access computed property names like so... class Test { getProp(key) { return this[key] } } ... without receiving Element implicitly has an…
3
votes
1 answer

How to specify an interface that must have at least two properties of specific types

This is for the options of a select box. The options must each have one string property that serves as an id, and another property that represents what will be displayed -- in this case a ReactNode, however, I don't care what these are called only…
kaan_a
  • 3,503
  • 1
  • 28
  • 52
3
votes
2 answers

Typing a single Record entry

I'm looking for a TypeScript type definition that describes an object with a single property (having any value). I know that thare are index signatures, e.g. type X = { [key: string]: any } or alternatively type X = Record However…
scythe
  • 31
  • 1
3
votes
1 answer

Typescript: Using a tuple as index type

Given is a tuple of some keys like ["a", "b", "c"] and a nested object with those keys as properties {a: {b: {c: number}}}. How do you recursively use the members of the tuple as index in typescript? A implementation without proper typing: function…
MaximilianMairinger
  • 2,176
  • 2
  • 15
  • 36
3
votes
1 answer

No index signature with a parameter of type 'string' was found on type 'typeof Object'

I made a class doing like enum following: https://stackoverflow.com/a/51398471 export default class Juice { [key: string]: any; static APPLE = new Juice('APPLE', 'Apple juice'); static ORANGE = new Juice('ORANGE', 'Orange juice'); private…
dotorimook
  • 63
  • 2
  • 6
1
2 3 4 5