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.
One way to do this is by combining the custom fields with Record<string, string>
:
type Data = Record<string, string> & {
test: string;
foo?: boolean;
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.