Here is the given code rewritten in TypeScript:
type NullableDate = Date | null;
function calculateAgeAtDeath(DeathDay: NullableDate, Birthday: NullableDate): string {
if (!DeathDay || !Birthday) return '';
const deathDay = DeathDay;
let ageAtDeathDayCandidate = deathDay.getFullYear() - Birthday.getFullYear();
const ageAtDeathDay = Birthday > new Date(deathDay.setFullYear(deathDay.getFullYear() - ageAtDeathDayCandidate))
? ageAtDeathDayCandidate - 1
: ageAtDeathDayCandidate;
const yearsString = CountToStringHelper.countToCustomString(ageAtDeathDay, "год", "года", "лет");
if (ageAtDeathDay >= 3) return yearsString;
const dateAgeYearsAgo = new Date(deathDay.setFullYear(deathDay.getFullYear() - ageAtDeathDay));
let months = 0;
let dateForCalculatingMonths = new Date(dateAgeYearsAgo.setMonth(dateAgeYearsAgo.getMonth() - 1));
while (dateForCalculatingMonths >= Birthday) {
months++;
dateForCalculatingMonths = new Date(dateForCalculatingMonths.setMonth(dateForCalculatingMonths.getMonth() - 1));
}
const monthsString = CountToStringHelper.countToCustomString(months, "месяц", "месяца", "месяцев");
const days = Math.floor((dateAgeYearsAgo.getTime() - Birthday.getTime()) / (1000 * 60 * 60 * 24));
const daysString = CountToStringHelper.countToCustomString(days, "день", "дня", "дней");
return ageAtDeathDay > 0
? months > 0
? `${yearsString} ${monthsString}`
: yearsString
: months > 0
? monthsString
: daysString;
}
// Assuming CountToStringHelper is defined elsewhere with a static method countToCustomString.
class CountToStringHelper {
static countToCustomString(count: number, singular: string, dual: string, plural: string): string {
// Actual implementation of counting to custom string logic based on count value.
// This needs to be implemented or adapted from C# code.
return ""; // Placeholder implementation
}
}
Key Points:
- TypeScript Types: I defined
NullableDate as a union type for Date | null.
- Date Manipulation: In TypeScript, the Date object's methods like
getFullYear() and setFullYear() are used for date manipulation.
- CountToStringHelper: The
CountToStringHelper is assumed to have a method countToCustomString, handling the string formatting based on counts. You need to implement this function similarly to your C# version.
- No Built-in
string.Empty: TypeScript returns an empty string with ''.
This conversion assumes that CountToStringHelper.countToCustomString is implemented and available in the TypeScript environment, with functionality similar to its C# counterpart.