首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何做这种类型-安全:“类型'Vehicle<C>‘和'Vehicle<CarConfig>’没有重叠”

如何做这种类型-安全:“类型'Vehicle<C>‘和'Vehicle<CarConfig>’没有重叠”
EN

Stack Overflow用户
提问于 2022-01-21 08:25:25
回答 1查看 23关注 0票数 0

这个代码(这很奇怪,但我这么做只是为了提出这个问题):

代码语言:javascript
复制
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")
}

使用此错误进行编译:

代码语言:javascript
复制
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的正确方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-21 08:33:20

要走的道路是一个受歧视的工会:

代码语言:javascript
复制
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") 
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70798338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档