microsoft / microsoft/TypeScript
Function declarations inside function expressions should inherit control flow narrowings of the parent function expression
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.3k
- Merge medio
- 2g 4h
- PR unite (30g)
- 132
Descrizione
I am trying to avoid typing null checks for properties that are formerly optional on the outer interface, but are then assigned with default values for the whole context of the function body.
I used a type guard for it, the problem is that the guarded type is lost in a function, but not lost in an arrow function, even though it can't be hoisted before the type guard.
I don't want to introduce new variables for every function parameter in a similar manner and I don't want to call other functions with casting as printMenu(options as DefinedOptions).
TypeScript Version: 3.7.3, 3.8.0-beta
Search Terms:
typescript type guard function arrow function
Code
export interface Options {
header?: string
border?: boolean
pageSize?: number
helpMessage?: string
showKeypress?: boolean
}
interface DefinedOptions extends Options {
pageSize: number
helpMessage: string
}
const isType = <T>(arg: any): arg is T => true
export default async function menu(options: Options) {
options // Options
options.pageSize = options.pageSize ?? 0
options.helpMessage = options.helpMessage ?? 'Default message'
if (!isType<DefinedOptions>(options)) return null
options // DefinedOptions
return new Promise((resolve, reject) => {
function handleMenuKeypress(key: any) {
options // Options - should be DefinedOptions
printMenu(options) // error
}
const candleMenuKeypress = (key: any) => {
options // DefinedOptions
printMenu(options) // no error
}
})
}
function printMenu(options: DefinedOptions) {
}
Expected behavior:
Type should be DefinedOptions in both.
Actual behavior:
Type is Options in function but DefinedOptions in arrow function.
Related:
#10927
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
Riproduci l’esempio nel TypeScript Playground collegato usando le versioni di TypeScript riportate e confronta i tipi inferiti per la funzione annidata e la funzione freccia. Il lavoro è completato quando entrambe le forme mantengono il narrowing di DefinedOptions dell’espressione di funzione padre senza cast o variabili aggiuntive.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- typescript
- Ambito
- compilers
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100