首页 > 解决方案 > Typescript Exclude 拒绝泛型类型

问题描述

这是一个最小的可重现示例

type Value = {}

type Something = {}

function isValid<T>(a: Exclude<T, Value>) { }

function selecter<T extends Something>(obj: T) {
    isValid(obj)
}

export { }

Typescript 3.8.3 拒绝isEqual(obj)表达式

Type 'Something' is not assignable to type 'Exclude<T, Value>

但是Type Something是可分配的!这有效:

let s: Something = {}
isValid(s)

错误消息不是错误吗?如何使isValid接受除Value之外的任何类型?

标签: typescript

解决方案


为 isValid 的参数键入不匹配。

type Something {}

function isValid<T>(a: T) { }

function selecter<T extends Something>(obj: T) {
  isValid(obj)
}

推荐阅读