Typescript 向对象包装器添加类型
我正在尝试向包装对象和数组的类添加类型。我可以很容易地为物体做这件事Typescript 向对象包装器添加类型,typescript,Typescript,我正在尝试向包装对象和数组的类添加类型。我可以很容易地为物体做这件事 interface IObject1 { value1: string, } interface IObject2 { myObject: IObject1, myObjects: IObject1[] } interface Wrapper<T>{ $<K extends keyof T>( selection: K ): Wrapper<T[K
interface IObject1 {
value1: string,
}
interface IObject2 {
myObject: IObject1,
myObjects: IObject1[]
}
interface Wrapper<T>{
$<K extends keyof T>(
selection: K
): Wrapper<T[K]>;
}
const wrappedObject2: Wrapper<IObject2> = undefined as any;
//This correctly get the type Wrapper<IObject1>
const wrappedObject1 = wrappedObject2.$('myObject');
我不喜欢这个解决方案的原因是wrappedObject1和wrappedObject1InsideArray具有Wrapper类型。由于IObject1与t extends any不兼容,因此不应该发生的事情[]
所以我想知道是否有更好的方法来解决这个问题。是的,似乎是这样。与其如此,不如这样:
interface Wrapper<T> {
$<K extends keyof T>(
selection: K
): Wrapper<T[K]>;
$<A>(this: Wrapper<A[]>, selection: number): Wrapper<A>
__brand?: T
}
一切都按预期进行,请注意,由于this参数不适用,因此如何阻止您调用expectedError中的第二个重载
好的,希望能有帮助。祝你好运 这正是我需要的。非常感谢。
interface Wrapper<T> {
$<K extends keyof T>(
selection: K
): Wrapper<T[K]>;
$<A>(this: Wrapper<A[]>, selection: number): Wrapper<A>
__brand?: T
}
const wrappedObject2: Wrapper<IObject2> = undefined as any;
const wrappedObject1 = wrappedObject2.$('myObject');
const expectedError = wrappedObject2.$('myObject').$(0); // IObject1 is not an array
const wrappedObject1InsideArray = wrappedObject2.$('myObjects').$(1);