Hello everyone,
I have a TypeScript question regarding the ability to capture the "exact type" of a variable that has been explicitly typed with an interface. Here's a quick example to illustrate:
interface ExampleInterface {
example?: number,
obj?: {
innerExample?: boolean,
somethingElse?: number | string
}
}
const test: ExampleInterface = {
example: 1,
obj: {
innerExample: true
}
}
type newTest = typeof test;
In the code above, newTest is inferred to be of type ExampleInterface. However, I'm interested in capturing the exact type of test, ie.
type newTest = {
example: 1,
obj: {
innerExample: true
}
}
Removing the ExampleInterface type from test isn't ideal, as I'd lose IntelliSense and type checking.
I tried using a helper function to get around this limitation:
function ExampleInterface<T extends ExampleInterface>(example: T): T {
return example;
}
const test = ExampleInterface({
example: 1,
obj: {
innerExample: true
},
thisShouldNotBeAllowed: true // But this should not be allowed
});
type newTest = typeof test;
While the helper function helps me capture the exact type I want for newTest, it also allows any properties that extend ExampleInterface. This is not what I'm aiming for.
So, is there a way to get the best of both worlds? I'd love to hear your thoughts and suggestions. Thank you in advance!