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
0
votes
0 answers

converting string value to enum type value

I have created a enum in typescript: export enum ProductType { FRUIT, CLOTH, } I wonder if I receive string value fruit and cloth, how can I convert the string to the enum type. Here is what I tried: const value: string = 'fruit'; // compiler…
user842225
  • 5,445
  • 15
  • 69
  • 119
0
votes
0 answers

Typescript Interface Properties with Index Signature for Defined Properties Only

I am trying out an API using Typescript with local json file as storage (to test things out). I defined two interfaces, one for the DB model and one for the input from the request, with the model extending from the input interface, as the…
hakuna matata
  • 3,243
  • 13
  • 56
  • 93
0
votes
1 answer

How to remap an index signature to make keys detectable in IDE

So, I'm trying to create an object that can have dynamic attributes, but I want that the IDE can be able to detect the keys that I'm already gave to this object. if I try this example: interface Person { name: string age: number } type…
Forsaiken
  • 324
  • 3
  • 12
0
votes
1 answer

Typescript: How to remove key from index signature?

In my Angular based web application, we at some point needed a type to hold translations of various strings in different languages. A colleague then implemented this type for that purpose: export class TranslatedString { [language: string]:…
Chris
  • 1,417
  • 4
  • 21
  • 53
0
votes
1 answer

Creating an index signature in Typescript with required AND optional keys

I'm trying to find a more elegant solution for creating a type that allows certain keys of it's index signature to be optional. This may be a use case for generics, but I can't seem to crack it. Currently constructing it like this: // Required and…
hebtwo
  • 1
0
votes
2 answers

Constraining an index signature (using generics) to make sub-properties have matching types

In TypeScript (v4.5.4), I am trying to define an object type via an index signature. I want TypeScript to enforce certain sub-properties in the object to have matching types, but those types are allowed to vary between top-level properties. In the…
sizzle beam
  • 555
  • 4
  • 10
0
votes
1 answer

Index signature where key is string vs [string]

What's the difference between these two? let foo:{ [index:string] : string } = { ['hello']: 'world' }; let bar:{ [index:string] : string } = { 'hello': 'world' }; I get the same result (world) when for the two…
McLovin
  • 3,295
  • 7
  • 32
  • 67
0
votes
1 answer

Add index signature to a function in .d.ts

I want to overwrite npm library typing to add index signature to a function. Let's say the function does nothing spectacular: export function foo(input) { return Number(input); } It has a typing in .d.ts file: export default function foo(input:…
Buszmen
  • 1,978
  • 18
  • 25
0
votes
1 answer

A generic change handler for text inputs using Typescript/React with dictionary type

I found this clever example of using a single change function to handle multiple text inputs and state changes for React and Typescript. The example, naturally, uses a normal string type: type MyEntity = { name: string; // would work with any…
MattoMK
  • 609
  • 1
  • 8
  • 25
0
votes
1 answer

Why does index signature of the object type accept an object with no properties?

I have a Dictionary interface where I want to have index type as string and values to be of string type. interface One { [key: string]: string; } If I annotated this type to a constant variable that holds an object with no properties, then it…
Subrato Pattanaik
  • 5,331
  • 6
  • 21
  • 52
0
votes
2 answers

Why typescript throws an index-signature error here?

In the function getName I loop through the static properties of the class UnitGroups. The function should return the property's identifier fitting to the passed value. E.g. UnitGroups.getName(1) should return "Speed". export default class…
0
votes
2 answers

Strongly typing Twitter widget to get rid of member access errors

I'm having difficulty strongly typing my Twitter widget. At the moment, it throws me a bunch of errors including: ESLint: Unsafe call of an any typed value.(@typescript-eslint/no-unsafe-call) ESLint: Unsafe member access .catch on an any…
methuselah
  • 12,766
  • 47
  • 165
  • 315
0
votes
1 answer

Typescript: How to reference property name in an string index signature definition in an interface

Illustration export interface IEventDef { ready: any, } export interface IIPCMessage { eventType: keyof IEventDef, data: IEventDef[this['eventType']] } interface IMessageHandlers { [eventName: keyof IEventDef]: (data: ) =>…
Mohamed Allal
  • 17,920
  • 5
  • 94
  • 97
0
votes
2 answers

Index signature for iteration in typescript

We can all see that this code is valid javascript: const myObj = { foo: "string", bar: 123, baz: "important stuff" }; ['foo', 'bar'].forEach((key) => { delete myObj[key]; }); Element implicitly has an 'any' type because expression of type…
MrMamen
  • 359
  • 2
  • 14
0
votes
1 answer

Extending an interface with index signature in generic while having typing for implementations

I have a system that takes key:object pairs and then lets you get them later in the application. The problem is having this index signature on breaks the typing because it allows any key at all to exist so you can't type the get() requests. A…
sailingonsound
  • 113
  • 1
  • 7