“‘T’ 可能被实例化为任意类型” 错误。

huangapple go评论65阅读模式
英文:

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&lt;T&gt; = T &amp; (T extends MyType ? ({
    myArg?: MyInterface&lt;T&gt;
    })
  : 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 = &#39;foo&#39;;

interface MyInterface&lt;T extends MyType&gt; {
    myField: T;
}

type ArgType&lt;T&gt; = T &amp; (T extends MyType ? ({
    myArg?: MyInterface&lt;T&gt;
    })
  : never)

function myFunc&lt;T&gt;(arg: ArgType&lt;T&gt;) {
    return arg;
}

class MyClass&lt;T extends MyType&gt; implements MyInterface&lt;T&gt; {
    constructor(readonly myField: T) {}
    invoke() {
        const result = myFunc({
            myArg: this
        });
    }
}

Playground link

答案1

得分: 0

type MyType = 'foo';

interface MyInterface {
myField: T;
}

type ArgType = T extends MyType ? {
myArg?: MyInterface;
} : never;

function myFunc(arg: ArgType) {
return arg;
}

class MyClass implements MyInterface {
constructor(readonly myField: T) {}
invoke() {
const result = myFunc({
myArg: this
});
}
}

英文:
type MyType = &#39;foo&#39;;

interface MyInterface&lt;T extends MyType&gt; {
    myField: T;
}

type ArgType&lt;T&gt; = T extends MyType ? {
    myArg?: MyInterface&lt;T&gt;;
} : never;

function myFunc&lt;T&gt;(arg: ArgType&lt;T&gt;) {
    return arg;
}

class MyClass&lt;T extends MyType&gt; implements MyInterface&lt;T&gt; {
    constructor(readonly myField: T) {}
    invoke() {
        const result = myFunc&lt;MyType&gt;({
            myArg: this
        });
    }
}

huangapple
  • 本文由 发表于 2023年5月17日 22:18:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定