有没有办法只在打字稿中将泛型类型限制为普通对象?

sid*_*shi 9 javascript typescript

使用打字稿,有没有办法限制泛型类型只允许类型对象的值?不是数组和其他类型。

例如:

function check<O extends object>(ob: O): O {
  return ob
}

check({}) // should be fine
check([]) // should show error, but does not.
Run Code Online (Sandbox Code Playgroud)

一个可能的现实世界用例:

function extend<A extends object, B extends object>(a: A, b: B): A & B {
  return {
    ...a,
    ...b,
  };
}

// This is fine, return type is { x: number } & { y: string }
extend({x: 5}, {y: "str"})

// This should not be allowed
// Return type is number[] & string[]
// Accessing a property yields impossible types like number & string
extend([1,2,3], ["s", "i", "d"])

// More examples for variants which I don't want to allow
extend({}, function() {})
extend({}, new Map())
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 6

您可以使用条件类型添加到参数 if Oextends的参数any[]。您添加的内容可以确保调用将是错误的。我通常添加字符串文字类型并将它们视为自定义错误消息:

function check<O extends object>(ob: O & (O extends any[] ? "NO Arrays !" : {})): O
function check<O extends object>(ob: O): O {
  return ob
}

check({}) // should be fine
check([]) // error
Run Code Online (Sandbox Code Playgroud)

  • @bugs 与条件的交集往往会干扰其他东西,不是对于这个简单的例子,但我认为最好将条件签名分开,你也可以只用一种类型来做到这一点。 (2认同)