TypeScript中泛型类型子类的推断

时间:2017-08-10 13:59:22

标签: typescript type-inference typescript-generics

我希望有一个函数,它接受一些对象并返回其x属性。该对象需要限制为泛型类型Type<X>,我希望返回值的类型是属性x的类型。

要将输入限制为Type<X>,我需要使用T extends Type<X>,但我必须将X实际设置为某些类型的值,例如T extends Type<string>,这些值不会起作用使用Type<number>T extends Type<any>放弃x属性的类型信息。

我希望做<T extends Type<any>>(o: T) => T.X<T extends Type<???>>(o: T) => typeof o

之类的事情

TypeScript中有没有办法做到这一点?如果是这样,怎么样?

// Suppose I have this generic interface
interface Type<X> {
  readonly x: X
}

// I create one version for foo...
const foo: Type<string> = {
  x: 'abc',
}

// ...and another one for bar
const bar: Type<number> = {
  x: 123,
}

// I want this function to restrict the type of `o` to `Type`
// and infer the type of `o.x` depending on the inferred type of `o`,
// but to restrict to `Type` I must hardcode its X to `any`, which
// makes `typeof o.x` to evaluate to `any` and the type of `o.x` is lost.
function getX<T extends Type<any>> (o: T): typeof o.x {
  return o.x
}

// These are correctly typed
const okFooX: string = getX(foo)
const okBarX: number = getX(bar)

// These should result in error but it is OK due to `Type<any>`
const errorFooX: boolean = getX(foo)
const errorBarX: boolean = getX(bar)

0 个答案:

没有答案