0

打字稿游乐场

我希望能够使用Getter接口的实现,或者在泛型中指定返回类型,或者在标准类型分配中描述返回类型。在这两种情况下,类型都需要看起来像一个简单的对象,所以我扩展 aRecord以在类型不匹配时鼓励编译器错误(如number, 或string)。

当没有提供类型时,假设它是一个无类型的简单对象。

目前,它未能说明:

Property 'bar' is missing in type 'Record<string, any>' but required in type 'Foo'.

然而Foo是一个“简单”的对象

type SimpleObject = Record<string, any>

interface Getter<T extends SimpleObject = SimpleObject> {
  getBody(): T
}

type Foo = {
  bar: string
}

// Case 1: Assume a simple object when no type information is supplied
void function () {
  const getter: Getter = {} as any

  const value = getter.getBody()
}

// Case 2: Use generic parameter to assign type when specified
void function() {
  const getter: Getter<Foo> = {} as any

  const value = getter.getBody()
}

// Case 3: Use type assignment, but validate that the type is a "simple object"
void function() {
  const getter: Getter = {} as any

  // Fails
  const value: Foo = getter.getBody()
}
4

1 回答 1

0

回答

答案是在方法上添加第二个类型参数

interface Getter<T extends SimpleObject = SimpleObject> {
  getBody<T1 = T>(): T1
}
于 2020-03-29T22:44:33.840 回答