We have the following simplified code where we want to have a function using a list of BaseDescription, where each BaseDescription is of a different kind.
Whenever something is returned from test, the type information should still contain the original type. In the example code we have type Example, so we want result to be of type BaseDescription<Example>.
type Base = {
foo: string
};
type BaseDescription<T extends Base> = {
bar: String,
baz: () => T
};
const test = (baseDescriptions: BaseDescription<any>[]) => {
return baseDescriptions[0];
};
type Example = Base & {
qux: string
};
const description: BaseDescription<Example> = {
bar: 'bar',
baz: () => ({ foo: 'foo', qux: 'qux' })
};
const result = test([ description ]);
// result is of type BaseDescription<any>
// but we want BaseDescription<Example>
Things already tried:
- Using interfaces instead of types
- Trying to find the TypeScript equivalent of
<? extends Base>(coming from Java) - Trying to find raw types
- Using
<Base>, but then result will have typeBaseinstead ofExample
Is the described behaviour even possible? And if so, how?
EDIT: Thanks for the answers so far! Defenitly makes me understand TS better.
I want to clarify the question a bit more. The idea is that an array of different Types is passed in. I have craeted a new playground
Additions:
type Example = Base & {
qux: string
};
type OtherExample = Base & {
bla: string
};
const description: BaseDescription<Example> = {
bar: 'bar',
baz: () => ({ foo: 'foo', qux: 'qux' })
};
const otherDescription: BaseDescription<OtherExample> = {
bar: 'bar',
baz: () => ({ foo: 'foo', bla: 'qux' })
};
const [ first, second ] = test([ description, otherDescription ]);
I get the feeling that the thing that I want to achieve, will not be possible.