Soru
How do we write one generic useTransportation(..) method? 57
Çözüm
4.7331 Voting
Nihat
Usta · 5 yıl öğretmeniUzman doğrulaması
Cevap
Here is an example of a generic useTransportation(...) method that can be used in various transportation scenarios:<br />```typescript<br />function useTransportation<T>(transportation: T) {<br /> // Determine the appropriate transportation method based on the input<br /> let method: string;<br /> switch (transportation) {<br /> case 'car':<br /> method = 'drive';<br /> break;<br /> case 'train':<br /> method = 'ride';<br /> break;<br /> case 'plane':<br /> method = 'fly';<br /> break;<br /> default:<br /> method = 'walk';<br /> }<br /> // Use the determined method to perform the transportation<br /> console.log(`Using ${transportation} to ${method()}`);<br />}<br />```<br />In this example, the useTransportation(...) method takes in a generic parameter T that represents the type of transportation. The method then uses a switch statement to determine the appropriate transportation method based on the input, and then uses that method to perform the transportation. This allows the useTransportation(...) method to be used in a variety of transportation scenarios, while still maintaining type safety.
Derecelendirmek için tıklayın: