microsoft / microsoft/TypeScript
Type discrimination by static readonly symbol
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.3k
- Merge medio
- 1g 19h
- PR unite (30g)
- 117
Descrizione
🔍 Search Terms
"type discrimination", "discrimination", "symbol discriminator"
✅ Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
⭐ Suggestion
AFAIK it is impossible to discriminate types by a static symbol like this:
class Animal {
public static readonly symbol = Symbol()
}
if (obj[Animal.symbol] === something) {
// here types are not deduced correctly
}
In contrast, code like this works fine:
const animal_symbol = Symbol()
if (obj[animal_symbol] === something) {
// here types are not deduced correctly
}
Not sure if this is a bug or just not implemented due to some complications.
📃 Motivating Example
By using unique symbol in a class I can discriminate objects like this:
class Cat {
public static readonly symbol = Symbol(`Cat.symbol`)
public get symbol() : typeof Cat.symbol {
return Cat.symbol
}
public meow() {}
}
class Dog {
public static readonly symbol = Symbol(`Dog.symbol`)
public get symbol() : typeof Dog.symbol {
return Dog.symbol
}
public woof() {}
}
type AnimalUnion = Cat | Dog
function take_animal(animal : AnimalUnion) {
if (animal.symbol === Cat.symbol) animal.meow()
else if (animal.symbol === Dog.symbol) animal.woof()
else assert_never(animal, new Error)
}
function assert_never(never : never, error : Error) : never {
throw error
}
The main focus here is inside take_animal: we can know that animal has meow() method if animal.symbol === Cat.symbol.
In this particular case I used symbol key to store the symbol. But what if key is also a symbol?
Like this:
const animal_symbol = Symbol(`Animal.symbol`)
class Cat {
public static readonly [animal_symbol] = Symbol(`Cat.symbol`)
public get [animal_symbol]() : typeof Cat[typeof animal_symbol] {
return Cat[animal_symbol]
}
public meow() {}
}
class Dog {
public static readonly [animal_symbol] = Symbol(`Dog.symbol`)
public get [animal_symbol]() : typeof Dog[typeof animal_symbol] {
return Dog[animal_symbol]
}
public woof() {}
}
type AnimalUnion = Cat | Dog
function take_animal(animal : AnimalUnion) {
if (animal[animal_symbol] === Cat[animal_symbol]) animal.meow()
else if (animal[animal_symbol] === Dog[animal_symbol]) animal.woof()
else assert_never(animal, new Error)
}
function assert_never(never : never, error : Error) : never {
throw error
}
This example works fine and guarantee no name collisions between string key symbol and possible field in derived class.
But for some reason if I try to put animal_symbol in a static readonly property;
class Animal {
public static readonly symbol = Symbol(`Animal.symbol`)
}
class Cat {
public static readonly [Animal.symbol] = Symbol(`Cat.symbol`)
public get [Animal.symbol]() : typeof Cat[typeof Animal.symbol] {
return Cat[Animal.symbol]
}
public meow() {}
}
class Dog {
public static readonly [Animal.symbol] = Symbol(`Dog.symbol`)
public get [Animal.symbol]() : typeof Dog[typeof Animal.symbol] {
return Dog[Animal.symbol]
}
public woof() {}
}
type AnimalUnion = Cat | Dog
function take_animal(animal : AnimalUnion) {
if (animal[Animal.symbol] === Cat[Animal.symbol]) animal.meow()
else if (animal[Animal.symbol] === Dog[Animal.symbol]) animal.woof()
else assert_never(animal, new Error)
}
function assert_never(never : never, error : Error) : never {
throw error
}
The trick doesn't work anymore. Now take_animal() can't deduce meow() from animal[Animal.symbol] === Cat[Animal.symbol].
But I think it should.
💻 Use Cases
- What do you want to use this for?
I want to use this to introduce segregation not by string key, but by a symbol key stored asstatic readonly. - What shortcomings exist with current approaches?
It cannot usestatic readonlysymbols. - What workarounds are you using in the meantime?
I have to use symbols as global variables.
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
L'issue non indica file né test; inizia con gli esempi take_animal di Cat/Dog e riproduci la differenza tra un simbolo a livello di modulo e Animal.symbol. Traccia il comportamento del type checker per le proprietà di simbolo statiche in sola lettura, quindi aggiungi una copertura mirata che mostri il narrowing previsto e il comportamento esaustivo di assert_never.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- typescript
- Ambito
- compilers
- Tipo di issue
- Funzionalità
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100