这里是游乐场,这里是代码:
export interface Schema {
getTypes<R>(): R;
}
export interface Simulator<T extends string> {
tag: T;
schema: Schema;
}
const auth0Simulator: Simulator<"auth0"> = {
tag: "auth0",
schema: {
getTypes() {
return {
name: 'bob',
email: 'blue@text.com'
}
}
}
}
我得到这个错误:
Type '() =>{名称:字符串;电子邮件:字符串;}'不能赋值给类型'()=>R"。类型'{名称:字符串;电子邮件:字符串;}'不能赋值给类型'R'。'R'可以用任意类型实例化,该类型可能与'{name: string;电子邮件:字符串;}"。(2322)输入。tsx(2,3):期望的类型来自属性'getTypes',该属性在类型'Schema'上声明
我明白这个错误,但是我能做些什么来修复它吗?
首先,问题在于函数的泛型。如果你想让Typescript正确识别类型,你应该把它添加到接口声明中,像这样:
export interface Schema<R> {
getTypes(): R;
}
模拟器看起来像这样:
export interface Simulator<T extends string, R> {
tag: T;
schema: Schema<R>;
}
和它的实现类型定义像这样:
const auth0Simulator: Simulator<"auth0", User> = {
tag: "auth0",
schema: {
getTypes() {
return {
name: 'bob',
email: 'blue@text.com'
}
}
}
}
type User = {
name: string;
email: string;
}