我希望能够使用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()
}