0

Im trying to create an interface in Typescript which has an both Unkown key names and known key names. Something like this:

interface Data { 
    test: string,
    [key: string]: string,
    foo?: boolean,
}

So that im able to do this:

x: Data = {
  test: "test_string",
  "unknown_key": "value"
}

Anyone know how im able to do this? Thanks.

Luffy
  • 15
  • 1
  • 8
  • 1
    The possible types of `[key: string]` must cover the types of all the other properties, so in your case `[key: string]: string | boolean | undefined`. – Sergiu Paraschiv Dec 07 '20 at 16:10

2 Answers2

0

One way to do this is by combining the custom fields with Record<string, string>:

type Data = Record<string, string> & { 
  test: string;
  foo?: boolean;
}
SimpleJ
  • 13,812
  • 13
  • 53
  • 93
-1

Here you have an example:


// You can omit `test` property in Data interface since it has a string type
interface Data { 
    [key: string]: string,
    foo?: boolean,
}

// You can use Verify helper instead of Data interface. It is almost the same
type VerifyT<T> = { foo?: boolean } & { [K in keyof T]: K extends "foo" ? unknown : string };

const make = <T extends VerifyT<T>>(t: T) => t;
make({ age: 'sdf', foo: true }) // Ok
make({ age: 'sdf', foo: undefined }) // ok
make({ age: 'sdf', foo: undefined }) // false
make({ age: 'sdf', foo: 'some text' }) // error
make({ age: 'sdf', foo: 1 }) // error
make({ age: 'sdf', foo: [1] }) // error

Don't worry about function overhead, because if you use V8 engine, it will be 99% inlined and optimized

All gredits goes to this answer.

Also feel free to marks this question as a dublicate