[英]Is there a way to constraint a generic type to plain objects only in typescript?
使用打字稿,有没有办法限制泛型类型只允许类型对象的值? 不是数组和其他类型。
例如:
function check<O extends object>(ob: O): O {
return ob
}
check({}) // should be fine
check([]) // should show error, but does not.
一个可能的现实世界用例:
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())
如果O
extends 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
在较新版本的 Typescript 中,您可以使用object & Exclude<T, any[]>
来表示不能是数组的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.