这个代码(这很奇怪,但我这么做只是为了提出这个问题):
interface Vehicle<C> {
id: string
name: string
config: C | null
}
interface CarConfig {
leatherSeats: boolean
}
const Car: Vehicle<CarConfig> = {
id: "car",
name: "car",
config: null
}
interface TruckConfig {
numberOfWheels: number
}
const Truck: Vehicle<TruckConfig> = {
id: "truck",
name: "truck",
config: null
}
function getVehicleConfig<C>(vehicle: Vehicle<C>): C | null {
if (vehicle === Car) {
return vehicle.config
}
if (vehicle === Truck) {
return vehicle.config
}
throw new Error("Unknown vehicle")
}使用此错误进行编译:
src/explain.ts:28:9 - error TS2367: This condition will always return 'false' since the types 'Vehicle<C>' and 'Vehicle<CarConfig>' have no overlap.这里的期望是(由于软件的另一部分中的约束),getVehicleConfig中的getVehicleConfig总是Car对象或Truck对象,getVehicleConfig将返回与实例关联的配置。
以一种类型安全的方式表达getVehicleConfig的正确方法是什么?
发布于 2022-01-21 08:33:20
要走的道路是一个受歧视的工会:
type VehiculeType= 'Car' | 'Truck';
interface Vehicle<C> {
id: string
name: string
config: C | null
type: VehiculeType;
}
interface CarConfig {
leatherSeats: boolean
}
const Car: Vehicle<CarConfig> = {
type: 'Car',
id: "car",
name: "car",
config: null
}
interface TruckConfig {
numberOfWheels: number
}
const Truck: Vehicle<TruckConfig> = {
type: 'Truck',
id: "truck",
name: "truck",
config: null
}
function getVehicleConfig<C>(vehicle: Vehicle<C>): C | null {
if (vehicle.type === 'Car') {
return vehicle.config
}
if (vehicle.type === 'Truck') {
return vehicle.config
}
throw new Error("Unknown vehicle")
}https://stackoverflow.com/questions/70798338
复制相似问题