Default Type Parameters की जानकारी
In this page:
interface InterfaceName<T = DefaultType> {
value: T;
}
Basic Default Type Parameter
एक default type, type parameter के बाद एक equals sign उपयोग करके assign होता है (T = string, उदाहरण के लिए), और वह default अपने आप उपयोग होता है जब भी caller एक type argument supply नहीं करता।
उदाहरण: Basic Default Type Parameter
interface Box<T = string> {
value: T;
}
const b: Box = { value: "hello" };
console.log(b.value);
Overriding the Default
Call site पर explicitly एक और type argument supply करके एक default type हमेशा override किया जा सकता है, तो default सिर्फ common case के लिए एक convenience है, कोई hard restriction नहीं।
उदाहरण: Overriding the Default
interface Box<T = string> {
value: T;
}
const b: Box<number> = { value: 42 };
console.log(b.value);
Default Types in Generic Functions
Generic functions defaults define कर सकते हैं, जो उपयोगी है जब एक particular type assume किया जाना चाहिए जब तक caller के पास इससे deviate करने का कोई specific कारण न हो।
उदाहरण: Default Types in Generic Functions
function wrap<T = string>(value: T): T[] {
return [value];
}
console.log(wrap("hi"));
console.log(wrap<number>(5));
Default Types in Classes
Generic classes defaults provide कर सकती हैं ताकि class का common, everyday उपयोग हर बार instantiate करते समय एक explicit type argument लिखने की ज़रूरत न रखे।
उदाहरण: Default Types in Classes
class Container<T = string> {
constructor(public value: T) {}
}
const c = new Container("default");
console.log(c.value);
Multiple Default Type Parameters
एक generic declaration में एक साथ कई default type parameters हो सकते हैं, हालांकि कोई भी required (non-default) type parameters हमेशा उन्हें पहले आना चाहिए जिनके defaults हैं, बिल्कुल जैसे default function parameters काम करते हैं।
उदाहरण: Multiple Default Type Parameters
interface Pair<A, B = string, C = number> {
first: A;
second: B;
third: C;
}
const p: Pair<boolean> = { first: true, second: "x", third: 1 };
console.log(p);
- एक required type parameter को default वाले के बाद रखना, जैसे
<T = string, U>, जो एक error है क्योंकि defaulted parameters आखिर में आने चाहिए। Box<>लिखना या default के apply होने की उम्मीद करना जब आप एक गलत argument दें, जब एक default सिर्फ एक missing argument fill करता है।- यह मान लेना कि default उपयोग होगा जब TypeScript
Tinfer कर सकता है, जब एक function argument से inference default से जीतता है।
- Generics functions, interfaces, और classes को type safety रखते हुए कई types के साथ काम करने देते हैं।
extendsऔरkeyofoperator वाले Constraints यह सीमित करते हैं कि एक type parameter क्या हो सकता है।- Classes और functions flexible reusable code के लिए multiple type parameters और default type parameters उपयोग कर सकते हैं।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: