typescript - Genel birleşim türünü N’den fazla tür olmasına izin verecek şekilde kısıtlayın
Genel tipin kabul edebileceği birleşik tiplerin sayısını nasıl kısıtlayacağım hakkında herhangi bir bilgi bulamadım.
Kısmen ilgili tek konu burada bulunabilir https://github.com/microsoft/TypeScript/issues/13298 ama yine de, benim başarmayı hedeflediğim şey bu değil.
Aşağıdaki koda sahip olduğumu düşünürsek:
enum Currency {
EUR = "eur",
USD = "usd",
PLN = "pln",
RUB = "rub"
}
type Token<T extends Currency = Currency> = {
type: T;
value: string;
};
const token1: Token<Currency.EUR> = {
type: Currency.EUR,
value: "1"
}
const token2: Token<Currency.USD> = {
type: Currency.USD,
value: "1"
}
const currencies = [token1, token2];
const currencyNonUnion = token1.type; // is Currency.EUR
const currencyUnion = currencies[0].type; // // is Currency.EUR | Currency.USD
// should return never when T is not a union type and forward T in other when it's a union type
// MoreThanOne<Currency.EUR, Currency> // never
// MoreThanOne<Currency.EUR | Currency.ETH, Currency> // Currency.EUR | Currency.ETH
type MoreThanOne<T, R> = T
const foo = <T>(curr: MoreThanOne<T, Currency>) => { /// }
// should work
foo(currencyUnion);
// shuld fail
foo(currencyNonUnion);
(typescript oyun alanı)
MoreThanOne genel yardımcı tür, birleşim türü değilse never döndürmelidir. Yukarıdaki gereklilik göz önüne alındığında, ikinci foo çağrısı derleme zamanında hata vermelidir.