Typescript 为什么TS在使用条件类型时抛出错误?
我正在尝试将条件类型与Typescript一起使用,但tsc抛出了一个错误Typescript 为什么TS在使用条件类型时抛出错误?,typescript,Typescript,我正在尝试将条件类型与Typescript一起使用,但tsc抛出了一个错误 interface Player { name: string; position: string; leg: string; } interface Coach { name: string; licence: string; } type Role = 'coach' | 'player'; function getPerson<T extends Role>
interface Player {
name: string;
position: string;
leg: string;
}
interface Coach {
name: string;
licence: string;
}
type Role = 'coach' | 'player';
function getPerson<T extends Role>(role: T): T extends 'coach' ? Coach : Player {
if (role === 'coach') {
return {} as Coach; // Type 'Coach' is not assignable to type 'T extends "coach" ? Coach : Player'
} else {
return {} as Player; // Type 'Player' is not assignable to type 'T extends "coach" ? Coach : Player'
}
}
const person = getPerson('coach'); // const person: Coach
const person2 = getPerson('player'); // const person2: Player
界面播放器{
名称:字符串;
位置:字符串;
腿:弦;
}
接口教练{
名称:字符串;
牌照:字串;;
}
类型角色='coach'|'player';
函数getPerson(角色:T):T扩展“coach”?教练:球员{
如果(角色=='coach'){
返回{}作为Coach;//类型'Coach'不可分配给类型'T扩展“Coach”?Coach:Player'
}否则{
返回{}作为玩家;//类型'Player'不可分配给类型'T扩展“coach”?coach:Player'
}
}
const person=getPerson('coach');//警察:教练
const person2=getPerson('player');//警察2:玩家
有人能给我解释一下为什么它不起作用吗?我应该如何重构代码以获得合适的类型?条件类型在TS中不能以这种方式工作 让我们来看下一个示例:
接口教练{
名称:字符串;
牌照:字串;;
}
类型角色='coach'|'player';
函数getPerson(角色:角色):T扩展“coach”?教练:球员{
如果(角色=='coach'){
常数x=角色;
当T扩展'coach'时返回{}?coach:Player;//无错误
}否则{
当T扩展'coach'时返回{}?coach:Player;//无错误
}
}
const person=getPerson('coach');//警察:教练
const person2=getPerson('player');//警察2:玩家
上面的示例毫无帮助,但它向您展示了TS如何处理返回类型
你应该使用重载
界面播放器{
名称:字符串;
位置:字符串;
腿:弦;
}
接口教练{
名称:字符串;
牌照:字串;;
}
类型角色='coach'|'player';
功能getPerson(角色:T):玩家
功能getPerson(角色:T):教练
功能getPerson(角色:T){
如果(角色=='coach'){
常数x=角色;
返回{}作为Coach;
}否则{
以玩家身份返回{}
}
}
const person=getPerson('coach');//警察:教练
const person2=getPerson('player');//警察2:玩家
这是否回答了您的问题?