Ant*_*osa 5 generics typescript
我正在寻找类似于 Typescript 泛型专业化的东西,其中实现可以根据类型标准脱节。
一个最小的例子:
const someFunction = <A>() => { return 0; }
// something like this
<A extends String>someFunction = (a: A) => { return 1; }
<A extends Number>someFunction = (a: A) => { return 2; }
.
.
.
console.log(someFunction(false)); // prints 0
console.log(someFunction('string')); // prints 1
console.log(someFunction(42)); // prints 2
Run Code Online (Sandbox Code Playgroud)
这是我想要的“jist”。这在打字稿中可能吗?
Typescript 中不存在你所说的内容。最接近这个的是函数重载。根据您的示例,它看起来像这样:
function someFunction(a: boolean): 0
function someFunction(a: string): 1
function someFunction(a: number): 2
function someFunction(a: any) {
if(typeof a === 'boolean') {
return 0
} else if (typeof a === 'string') {
return 1
} else if (typeof a === 'number') {
return 2
}
}
Run Code Online (Sandbox Code Playgroud)
此示例适用于基元,typeof但也适用于复杂值和其他类型保护(包括用户定义的类型保护)。
| 归档时间: |
|
| 查看次数: |
1940 次 |
| 最近记录: |