在打字稿中,我不明白为什么我收到错误 'Service1 | Service2 | null' is not assignable to type '(Service1 & Service2) |无效的'
In typescript I don't understand why i getting the error 'Service1 | Service2 | null' is not assignable to type '(Service1 & Service2) | null'
我正在尝试为一个简单的个人应用程序创建一个“婴儿”IoC 容器。我试图用这段代码实现的是根据作为第一个参数
传递的键在方法registerService
中为参数service
定义类型
但我遇到了错误
Type 'Service1 | Service2 | null' is not assignable to type '(Service1 & Service2) | null'.
Type 'Service1' is not assignable to type 'Service1 & Service2'.
Property 'thing2' is missing in type 'Service1' but required in type 'Service2'.
我的代码:
export const SERVICE_ONE_KEY = 'service1'
export const SERVICE_TWO_KEY = 'service2'
type Service1 = {
thing1: () => void
}
type Service2 = {
thing2: () => void
}
type IocKeys = typeof SERVICE_ONE_KEY | typeof SERVICE_TWO_KEY
type Services = {
[SERVICE_ONE_KEY]: Service1 | null
[SERVICE_TWO_KEY]: Service2 | null
}
const registry: Services = {
service1: null,
service2: null
}
export const registerService = (name: IocKeys, service: Services[typeof name]): Services[typeof name] => {
registry[name] = service // Error here
return registry[name]
}
export const getService = (name: IocKeys): Services[typeof name] => {
return registry[name]
}
可以尝试一个“有效”的例子here来了解问题所在!
更新 1
我还想根据 getService
方法
中的名称参数键定义一个 return 类型
这可以通过 generics:
来实现
export const registerService = <T extends IocKeys>(name: T, service: Services[T]): Services[T] => {
registry[name] = service
return registry[name]
}
export const getService = <T extends IocKeys>(name: T): Services[T] => {
return registry[name]
}
我正在尝试为一个简单的个人应用程序创建一个“婴儿”IoC 容器。我试图用这段代码实现的是根据作为第一个参数
传递的键在方法registerService
中为参数service
定义类型
但我遇到了错误
Type 'Service1 | Service2 | null' is not assignable to type '(Service1 & Service2) | null'.
Type 'Service1' is not assignable to type 'Service1 & Service2'.
Property 'thing2' is missing in type 'Service1' but required in type 'Service2'.
我的代码:
export const SERVICE_ONE_KEY = 'service1'
export const SERVICE_TWO_KEY = 'service2'
type Service1 = {
thing1: () => void
}
type Service2 = {
thing2: () => void
}
type IocKeys = typeof SERVICE_ONE_KEY | typeof SERVICE_TWO_KEY
type Services = {
[SERVICE_ONE_KEY]: Service1 | null
[SERVICE_TWO_KEY]: Service2 | null
}
const registry: Services = {
service1: null,
service2: null
}
export const registerService = (name: IocKeys, service: Services[typeof name]): Services[typeof name] => {
registry[name] = service // Error here
return registry[name]
}
export const getService = (name: IocKeys): Services[typeof name] => {
return registry[name]
}
可以尝试一个“有效”的例子here来了解问题所在!
更新 1
我还想根据 getService
方法
这可以通过 generics:
来实现export const registerService = <T extends IocKeys>(name: T, service: Services[T]): Services[T] => {
registry[name] = service
return registry[name]
}
export const getService = <T extends IocKeys>(name: T): Services[T] => {
return registry[name]
}