英文:
Generic intersection results in "'T' could be instantiated with an arbitrary type" error
问题
以下是您提供的代码的翻译部分:
通用条件语句的评估被延迟执行,因此我正在尝试使用交集来提示编译器我的期望类型:
type ArgType<T> = T & (T extends MyType ? ({
myArg?: MyInterface<T>
})
: never)
然而,当我尝试调用一个访问上述参数类型的函数时,我遇到了以下错误:
'T' 可以用任意类型实例化,这个类型可能与 '{ myArg: this; }' 不相关。
完整代码:
type MyType = 'foo';
interface MyInterface<T extends MyType> {
myField: T;
}
type ArgType<T> = T & (T extends MyType ? ({
myArg?: MyInterface<T>
})
: never)
function myFunc<T>(arg: ArgType<T>) {
return arg;
}
class MyClass<T extends MyType> implements MyInterface<T> {
constructor(readonly myField: T) {}
invoke() {
const result = myFunc({
myArg: this
});
}
}
请注意,代码中的HTML实体编码已经被还原为正常的符号。如果需要更多帮助,请告诉我。
英文:
Generic conditionals have their evaluation deferred, so I am attempting to use an intersection to hint to the compiler my desired type:
type ArgType<T> = T & (T extends MyType ? ({
myArg?: MyInterface<T>
})
: never)
However, when I try to invoke a function that access an argument typed to the above, I am getting this error:
> 'T' could be instantiated with an arbitrary type which could be unrelated to '{ myArg: this; }'
Full code:
type MyType = 'foo';
interface MyInterface<T extends MyType> {
myField: T;
}
type ArgType<T> = T & (T extends MyType ? ({
myArg?: MyInterface<T>
})
: never)
function myFunc<T>(arg: ArgType<T>) {
return arg;
}
class MyClass<T extends MyType> implements MyInterface<T> {
constructor(readonly myField: T) {}
invoke() {
const result = myFunc({
myArg: this
});
}
}
答案1
得分: 0
type MyType = 'foo';
interface MyInterface
myField: T;
}
type ArgType
myArg?: MyInterface
} : never;
function myFunc
return arg;
}
class MyClass
constructor(readonly myField: T) {}
invoke() {
const result = myFunc
myArg: this
});
}
}
英文:
type MyType = 'foo';
interface MyInterface<T extends MyType> {
myField: T;
}
type ArgType<T> = T extends MyType ? {
myArg?: MyInterface<T>;
} : never;
function myFunc<T>(arg: ArgType<T>) {
return arg;
}
class MyClass<T extends MyType> implements MyInterface<T> {
constructor(readonly myField: T) {}
invoke() {
const result = myFunc<MyType>({
myArg: this
});
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论