首页 > 解决方案 > 打字稿中所有对象文字类型的子类型?

问题描述

假设strictFunctionTypes已打开,以便对函数参数进行反检查

interface Func<T> {
  (p: T): unknown
}
declare let b: Func<{p1: string}>
declare let c: Func<{p2: number}>
declare let d: Func<{p3: number, x: boolean, x1: number}>
// e, f, g... like before
let a: Func<U> // to make b, c, d, e, f... etc all assignable to a, what should U be
a = b
a = c
a = d

a应该可以使用 form 分配给所有可能的情况,有无限可能的有效值Func<{x: 1, y: string}>,我目前只能找到. 并对是否存在更受约束的人感到好奇。anyU

标签: typescript

解决方案


U需要是包含所有其他类型的类型,因此是所有类型的交集:

let a: Func<{p1: string, p2: number, p3: number, x: boolean, x1: number}>

推荐阅读