是否可以添加包装值的通用类型



让我们假设此代码:

interface PersonData {
  name: string
  age: number
}
class Component<T> {}
class PersonComponent extends Component<PersonData> {}
function foo<T>(component: Component<T>, data: any) {
  // How to specify the correct type for `data` when passing observables as shown below?
}
const personData = { name: Observable.of('John'), age: Observable.of(35) }
foo(new PersonComponent, personData)

换句话说:我希望能够指定接受T类型的data参数的类型,但其所有值都包裹在可观察的情况下。因此,我需要一种通常将T类型(是对象/记录(转换为同一类型的方法,其所有值都将其转换为可观察到。

和一个后续问题:是否可以将其扩展到深度嵌套的对象层次结构?

您可以使用映射的类型将组件支架映射到可观察的:

interface PersonData {
  name: string
  age: number
}
class Component<T> { p!: T}
class PersonComponent extends Component<PersonData> {}
type ObservableRecord<T> = {
    [P in keyof T]: Observable<T[P]>
}
function foo<T>(component: Component<T>, data: ObservableRecord<T>) {
}
const personData = { name: Observable.of('John'), age: Observable.of(35) }    
foo(new PersonComponent, personData) 

const personDataErr = { name: Observable.of('John'), age: Observable.of("35") }    
foo(new PersonComponent, personDataErr) // err

最新更新