PRA*_*SER 5 typescript typescript-generics
鉴于我们有如下两种不同的类型,我们如何根据字符串参数而不提供泛型类型来更改函数的返回值?
interface Type1 { typeName: string; };
interface Type2 { typeVersion: string; };
type AllTypes = Type1 | Type2;
function returnTypes(t: string): AllTypes {
...
}
const typeResult = returnTypes('type1');
console.log(typeResult.typeName);
Run Code Online (Sandbox Code Playgroud)
这里没有定义回报!
像这样创建一个重载声明
interface Type1 { typeName: string; };
interface Type2 { typeVersion: string; };
type AllTypes = Type1 | Type2;
function returnTypes(t: 'type1'): Type1;
function returnTypes(t: 'type2'): Type2;
function returnTypes(t : 'type1' | 'type2'): AllTypes {
switch (t) {
case "type1": return { typeName: "test" };
case "type2": return { typeVersion: "test" };
}
}
console.log(returnTypes('type1').typeName);
console.log(returnTypes('type2').typeVersion);
Run Code Online (Sandbox Code Playgroud)
请注意,当您以这种方式重载函数时,调用方无法使用实现签名。只有预先指定的声明才包含重载函数的接口。
更新:修复并完成示例以显示 TypeScript 知道它返回的是哪种类型。
| 归档时间: |
|
| 查看次数: |
5280 次 |
| 最近记录: |