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)
您可以使用条件类型添加到参数 if 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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1492 次 |
最近记录: |