首页 > 解决方案 > 类型鉴别器 - 如何限制参数

问题描述

假设我想做以下事情:

type Car = {
    type: 'car'
}

type House = {
    type: 'house'
}

add('car', {type: 'car'})   // < this is fine.

add('house', {type: 'car'}) // < this should cause a compile time error.

是否可以编写一个add强制执行此约束的方法?

type另一个要求是,您可以添加的内容没有限制。唯一的限制应该是types 必须匹配。

TS-游乐场链接

标签: typescriptgenerics

解决方案


稍微修改您的代码以使其按预期工作:

const add = <TObj extends {type: TKey}, TKey extends string>(key: TKey, obj: TObj) => {
    /* ... */
}

游乐场链接


推荐阅读