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
3
votes
1 answer

How to iterate through controls array property from Forms in Angular

I have the following problem I need to iterate through the controls property of a Form in Angular using a forEach loop. I am writing the following code: const arr = this.bankForm.controls; arr.forEach((element: {[key: string]: AbstractControl}) =>…
Luis
  • 2,006
  • 5
  • 31
  • 47
3
votes
2 answers

Type 'HTMLFormControlsCollection' has no property 'x' and no string index signature

The following error appears when trying to destructure a form.elements object: Type 'HTMLFormControlsCollection' has no property 'x' and no string index signature // in a class domRefs: {[key: string]: HTMLFormElement | null} = { myForm:…
Qwerty
  • 29,062
  • 22
  • 108
  • 136
2
votes
1 answer

Merging keys of two interfaces when passing to generic type

I have two interfaces as follows: interface Foo { foo: string; } interface Bar { prop1: string; prop2: string; } My goal is to create a type that combines these two interface keys with underline between them, something like this: type…
cyrus-d
  • 749
  • 1
  • 12
  • 29
2
votes
2 answers

Typescript class with index signature from passed type

I'm new to typescript and I'm trying to define a class properly that turns an object of a certain type to a class with the same properties. However, I can't properly define the keys on this class since they are generic: interface RawAnswer { …
Jonas Metzener
  • 133
  • 1
  • 8
2
votes
1 answer

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Type'

I am trying to trim the values from an array of objects that is returned from a REST API. This is the interface for the object I'm expecting. interface IProduct { productId: number; qty: number; code: string; customer: string; description:…
gmwill934
  • 609
  • 1
  • 10
  • 27
2
votes
1 answer

How to type object with index signature and dynamic variable in TypeScript?

I am new to TypeScript, and have tried various ways to type this, but running into problems with index signatures. What should the interface look like? interface MyConfig { ... } // someVar can be any string let someVar = "dynamicKey"; // the…
phifa
  • 856
  • 7
  • 11
2
votes
2 answers

Optional chaining for interfaces that have an index signature

I defined two interfaces. The first one has an optional field, the second one has an index signature: interface A { foo?: { bar: number }; } interface B { [s: string]: { bar: number }; } Why does the first interface give me a result of type…
2
votes
1 answer

Numeric index signature typescript class, get item count or access in general

I'm currently implementing an array-like typescript class. Is there a way to count the number of items in an indexed signature object in TypeScript? The class has got member functions and properties but should be accessible via the index signature.…
Felix Lemke
  • 6,189
  • 3
  • 40
  • 67
2
votes
1 answer

How to set index signature without opening up the interface

Consider this code: interface MyInterface { foo: string bar: string baz: string } const myObj: MyInterface = { foo: "foo", bar: "bar", baz: "baz" }; Object.keys(myObj).forEach(obj => { obj = myObj[obj]; }); When enabling strict mode…
MrMamen
  • 359
  • 2
  • 14
1
vote
2 answers

Unable to assign value to generically typed object

I am trying to assign a value to the property of a generically typed object passed into a function. The object structure is unknown in advance and the property name is dynamically provided to the function as a string argument. Typescript throws the…
Rob
  • 11
  • 2
1
vote
1 answer

Generic type with any property of certain type in typescript

Hi everyone! interface Thing { name: string; } interface ThingMap { [thingName: string]: Thing; } interface ThingMapClassA { first: { name: 'first thing name' }; second: { name: 'second thing name' }; third: { name: 'third thing name'…
1
vote
1 answer

How to create Record with dynamic string union property names that are optional?

I want to define an object type where the property names are pre-defined, but also optional. I want to create the equivalent of the below longer syntax, but is there a way to make it dynamic with optional properties so I could easily add / remove…
Advait Junnarkar
  • 3,283
  • 4
  • 13
  • 25
1
vote
1 answer

Passing string literals to index signatures

I've currently got MyTest which simply maps over an object: type MyTest = { [P in keyof T]: T[P]; }; type Result = MyTest<{hello: 'world', foo: 2}>; // ^? type Result = { hello: 'world', foo: 2 } However If I pass a string literal like…
stratis
  • 7,750
  • 13
  • 53
  • 94
1
vote
2 answers

TypeScript index signature with promises

What is the correct index signature for the following class? class MyClass { [index: string]: Promise | Promise; // not working public async methodOne (): Promise { ... } public async methodTwo (): Promise { ...…
Growth Mindset
  • 1,135
  • 1
  • 12
  • 28
1
vote
1 answer

Index Signature with Typescript with Array of Objects

I've been using Typescript for a few months now, but am stuck with getting my index signatures to work properly. sensorTestData = [ { altitude: 249.74905877223617 gas: 4361 humidity: 53.16487239957308 pressure: 30.100467823211194 …
dlubbers
  • 61
  • 8