typescriptindex-signature

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,
  txt: "TXT",
};

TS error:

Property 'length' of type 'number' is not assignable to string index type 'string'.

How should such an interface be typed?


Solution

  • [key: string]: string; this prevents the Foo interface to have none string properties (in your example, number).

    What you can do is to separate the known and unknown properties in two interfaces and define your target type as a union type like below:

    interface Foo {      
      length: number;
    }
    
    interface Bar {
        [key: string]: string ;
    }
    
    type FooBar = Foo | Bar;
    
    const foo : FooBar = {
      length: 1, // its ok defined in foo
      txt: "TXT", // string is ok
      baz : 3 // error because its not string
    };
    

    Playground Link