10

I would like to create an interface for an object that has a certain type for a specific named property and a different type for all other properties.

How would I write a definition for foo below?

let foo = {
   size: 3,
   a: 'foo',
   b: 'bar',
   c: 'baz'
}

This would be my intuitive approach:

interface Foo {
    size: number;
    [name: string]: string;
}

However, TypeScript tries to apply the general definition to the specific definition and triggers the following error:

error TS2411: Property 'size' of type 'number' is not assignable to string index type 'string'.
lyschoening
  • 18,170
  • 11
  • 44
  • 54

2 Answers2

7

You can do something like this (I don't know if it will work in TS v1.5):

interface Size {
    size: number;
}

interface StringMap {
    [name: string]: string;
}

type Foo = Size & StringMap;
franza
  • 2,297
  • 25
  • 39
  • You can also inline this if you'd like (also not 100% sure about ts 1.5). type Foo = {size: number} & {[name: string]: string}; – bingles Nov 13 '16 at 02:37
5

Without defining every property, that's expected, but you can do this:

interface Foo1 {
    size: number;
    [name: string]: string|number;
}

Better than using any.

thoughtrepo
  • 8,306
  • 2
  • 27
  • 21