Unique Symbols की जानकारी
In this page:
const sym: unique symbol = Symbol("description");
Declaring unique symbols
एक const symbol declaration को special unique symbol type मिलता है जब TypeScript को इसकी exact identity type level पर track करनी हो, न सिर्फ इसे general symbol type मानकर।
उदाहरण: Declaring unique symbols
const idKey: unique symbol = Symbol("id");
console.log(idKey);
Unique Symbol as a Discriminant
Unique symbols एक union में exact discriminants के रूप में act कर सकते हैं, क्योंकि हर एक precisely एक variant identify करता है — TypeScript यह narrow कर सकता है कि कौन सा specific unique symbol present है, सिर्फ 'कोई symbol' नहीं।
उदाहरण: Unique Symbol as a Discriminant
const circleTag: unique symbol = Symbol("circle");
const squareTag: unique symbol = Symbol("square");
type Shape =
| { tag: typeof circleTag; radius: number }
| { tag: typeof squareTag; side: number };
const s: Shape = { tag: circleTag, radius: 5 };
console.log(s.tag === circleTag);
Unique Symbols as Object Keys
एक unique symbol एक computed property key के रूप में उपयोग किया जा सकता है, एक interface को general symbol type के किसी arbitrary symbol के बजाय exactly एक symbol-keyed property refer करने देते हुए।
उदाहरण: Unique Symbols as Object Keys
const idKey: unique symbol = Symbol("id");
interface Entity {
[idKey]: number;
}
const e: Entity = { [idKey]: 1 };
console.log(e[idKey]);
Exact Symbol Identity
दो unique symbols अलग types माने जाते हैं भले ही उनकी description strings identical हों — यह identity-based typing TypeScript को distinct, non-forgeable tokens represent करने का एक कहीं ज़्यादा strong तरीका देती है।
उदाहरण: Exact Symbol Identity
const a: unique symbol = Symbol("token");
const b: unique symbol = Symbol("token");
console.log(a === (b as unknown as typeof a));
Practical Symbol Tokens
Unique symbols internal tokens के रूप में अच्छे से काम करते हैं जब एक API को strongly-typed identifiers चाहिए जिन्हें कभी गलती से एक ordinary string, number, या किसी और unrelated symbol के साथ confuse न किया जा सके।
उदाहरण: Practical Symbol Tokens
const AdminToken: unique symbol = Symbol("admin");
function checkAccess(token: typeof AdminToken) {
return "Access granted";
}
console.log(checkAccess(AdminToken));
- symbol को
letयाvarसे declare करना और एकunique symboltype की उम्मीद करना, जब सिर्फconstdeclarations qualify करती हैं। - same description वाले दो unique symbols compare करना और types match होने की उम्मीद करना, जब हर एक अपना खुद का type है।
- type position में symbol उपयोग करते समय
typeofभूल जाना, जैसेtag: idKeyबजायtag: typeof idKeyके।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: