Typescript nezjišťuje nesoulad typů
Mám funkci findFlightRecommendation. Vrací typ Flight.
export const findFlightRecommendation = <T>(state: IStore, sectorIds: T): Flight => {
if (!state || !state.search || !state.search.results) {
return undefined
}
...
return state.search.results.find(r => _.isEqual(r.sectorsId, sectorIds))
}
Tato funkce se používá k nalezení letu:
// state.personalData.sectorsKey is string[]
const flight = findFlightRecommendation(state, state.personalData.sectorsKey)
Později je tento objekt flight použit v jiné funkci jako parametr.
formatLoadingSubtitle(props.t, flight, getTravellers(state.form.searchForm.values)
Ale deklarace typů formatLoadingSubtitle říká, že let by měl být jako HasSectors:
export const formatLoadingSubtitle = (t: Translate, flight: HasSectors, travellers: number) => {
const departure = getDepartureTime(flight)
const arrival = getReturnTime(flight)
if (departure) {
return formatFlightDetails(t, departure, arrival, travellers)
}
}
Typy :
export interface Flight extends BasicFlightInfo {
mtk?: boolean
sectorsId?: string[]
sectorCodes?: string[]
handBaggage?: IHandBaggage
checkedBaggageIncluded?: boolean
leftSeats?: number
topRecommendationTag?: FilterSortByTypes
recommendationPriority?: number
}
export interface BasicFlightInfo extends HasSectors, FlightDebugInfo {
totalPrice: number
paxPrices: IPaxPrices
currency: string
offerFees: IOfferFees
totalDiscount?: number
cabinClasses?: string[]
}
interface HasSectors {
sectors: ISector[]
}
Odpověď č. 1
Neexistuje žádný problém, protože každý objekt implementující rozhraní Flight také implementuje HasSectors dědičně prostřednictvím BasicFlightInfo.
To znamená, že kdykoli se očekává HasSectors, může být použito cokoliv, co jej implementuje (tj. jakýkoli objekt implementující HasSectors, BasicFlightInfo nebo Flight).
Všechno funguje podle očekávání, žádná „neshoda typů“ není.