Closed
Description
π Search Terms
numeric index property access
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about index signatures
β― Playground Link
π» Code
// @target:ES2022
declare const o : {
[x:string]:'string'|'number'|'numstring',
[x:number]:'number'|'numstring',
[x:`${number}`]:'numstring'
}
const p1 = o[1]
// ^?
const p2 = o['1']
// ^?
const p3 = o['one']
// ^?
const p4 = o['0x0']
// ^?
const p5 = o['Infinity']
// ^?
const p6 = o[`${300n}`]
// ^?
const p7 = o['123_456']
// ^?
const p8 = o[123_456]
// ^?
const p9 = o['-1']
// ^?
const p10 = o['+1']
// ^?
const p11 = o[`${[6]}`]
// ^?
π Actual behavior
The inferred types of these index expressions are very unpredictable.
The indexes '1'
,'0x0'
,`${300n}`
, -1
, +1
are inferred as `${number}`
, and NOT as 'number'.
The indexes 1
, 'Infinity'
, 123_456
, are inferred as number
The indexes 'one'
, '123_456'
, '${[6]}'
are inferred as string
(these are understandable and not a problem)
π Expected behavior
I expect:
number
and${number}
to catch the same cases, since (I believe) they express the same intent as object keys. Likely they should be considered a duplicate index signature in the type declaration.'1'
and1
to be treated the same since they retrieve the identical property.+1
and0x0
to be inferred as non-numeric string, since (I think) the${number}
is supposed to be "the strings that a number may coerce to", not "the strings which are valid numeric literals". (though it's curious that strings containing binary, octal, and hex literals are accepted by the template string but NOT digit separators'123_456'
)- Possibly
${300n}
to be inferred as a non-numeric string. It's odd that it is treated as the string literal"300"
in the index but a non-literalstring
when initializing a const variable.
Additional information about the issue
Originally mentioned here.
This can surely be split into multiple issues.