When it comes to defining types, you have the option to use interfaces or types in TypeScript. If you opt for using types, you can achieve the following:
type AllowedKeys = "a" | "b";
export type TestType = {
[key in AllowedKeys]: Something;
};
This approach ensures that both keys specified in AllowedKeys are utilized within your defined type. An example scenario would be as follows:
An error will be raised with this code snippet:
const a: TestType = {
a: 'asd',
b: 'asd',
c: 'asd'
}
On the other hand, the following code is acceptable:
const a: TestType = {
a: 'asd',
b: 'asd',
}
However, even this will trigger an error:
const a: TestType = {
a: 'asd',
}
If utilizing all allowed keys is not necessary, you can denote optional keys by adding ?
to your type declaration:
export type TestType = {
[key in AllowedKeys]?: string;
};