Associated types in TypeScript
There is no such feature for associated types in Typescript at the moment.
Alternatives to Associated Types
While there isn't anything in Typescript like this?...
// WILL NOT COMPILE
interface Add<T> {
type Output;
add(other: T): Output;
}
There are alternatives that can address some of the problems that associated types address to varying degrees.
Inferring the generic
You can infer the type of passed to a generic like so
type ArrayItem<T> = T extends Array<infer I> ? I : never;
And you can use this type like this.
const number: ArrayItem<Array<number>> = 1;
You can play around with it here on the Typescript Playground here.
Indexing a field's field
Say you had some types like these:
type StorageStage<T> =
| { kind: 'initial' }
| { kind: 'loading', promise: Promise<Array<T>> }
| { kind: 'loaded', storage: Array<T> };
class AsyncStorage<T> {
state: StorageStage<T> = { kind: 'initial' };
}
You can use the index syntax to get the types of these fields if they're public.
const storageStage: AsyncStorage<number>["state"] =
{ kind: 'loaded', storage: [1] };
Again, you check this out on the Typescript Playground here.