如何基于 class 泛型定义泛型接口
how to define generic interface based on class generic
我正在尝试基于另一个接口创建一个新的增强型通用接口。基本接口定义对象将具有的属性 (root
)。扩充类型应具有相同的属性,但我得到的不是 any
作为值,而是一个更复杂的对象。请注意,接口 IStyleObj
在泛型 class 中使用,其中泛型类型传递给泛型接口。
在我的实验中我遇到了这些错误,但我不知道如何修复它们:
"IStyleObj<T>"
'T' is declared but its value is never read.ts(6133)
"Key in keyof"
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
Member '[K in keyof' implicitly has an 'any' type.ts(7008)
"... T"
Cannot find name 'T'.ts(2304)
"class: any"
'any' only refers to a type, but is being used as a value here.ts(2693)
这是我当前的代码:
// Child.ts
interface IStyles {
root?: any
}
// Base.ts
interface IStyleObj<T> {
[K in keyof T]: {
class: any
style: any
}
}
export default class Base<IStyles = {}> {
get styles (): IStyleObj<IStyles> {
// ...
}
}
接口不能映射类型,只有类型别名可以。这将起作用:
// Child.ts
interface IStyles {
root?: any
}
// Base.ts
type IStyleObj<T> = {
[K in keyof T]: {
class: any
style: any
}
}
export default class Base<IStyles = {}> {
get styles (): IStyleObj<IStyles> {
return null!
}
}
我正在尝试基于另一个接口创建一个新的增强型通用接口。基本接口定义对象将具有的属性 (root
)。扩充类型应具有相同的属性,但我得到的不是 any
作为值,而是一个更复杂的对象。请注意,接口 IStyleObj
在泛型 class 中使用,其中泛型类型传递给泛型接口。
在我的实验中我遇到了这些错误,但我不知道如何修复它们:
"IStyleObj<T>"
'T' is declared but its value is never read.ts(6133)
"Key in keyof"
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
Member '[K in keyof' implicitly has an 'any' type.ts(7008)
"... T"
Cannot find name 'T'.ts(2304)
"class: any"
'any' only refers to a type, but is being used as a value here.ts(2693)
这是我当前的代码:
// Child.ts
interface IStyles {
root?: any
}
// Base.ts
interface IStyleObj<T> {
[K in keyof T]: {
class: any
style: any
}
}
export default class Base<IStyles = {}> {
get styles (): IStyleObj<IStyles> {
// ...
}
}
接口不能映射类型,只有类型别名可以。这将起作用:
// Child.ts
interface IStyles {
root?: any
}
// Base.ts
type IStyleObj<T> = {
[K in keyof T]: {
class: any
style: any
}
}
export default class Base<IStyles = {}> {
get styles (): IStyleObj<IStyles> {
return null!
}
}