I'm encountering an issue with conditional typing in Typescript where tsc is throwing an error.
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
Can someone help me understand why this isn't working? How should I refactor my code to assign the proper types?