TypeScript/tests/cases/conformance/types/union/unionTypeWithIndexSignature.ts
Nathan Shively-Sanders c228924543
Index signatures contribute properties to unions (#25307)
* Index signatures contribute properties to unions

This means that in a union like this:

```ts
type T = { foo: number } | { [s: string]: string }
```

`foo` is now a property of `T` with type `number | string`. Previously
it was not.

Two points of interest:

1. A readonly index signature makes the resulting union property readonly.
2. A numeric index signature only contributes number-named properties.

Fixes #21141

* Correctly handle numeric and symbol property names

1. Symbol-named properties don't contribute to unions.
2. Number-named properties should use the numeric index signature type,
if present, and fall back to the string index signature type, not the
other way round.
2018-07-06 10:46:05 -07:00

28 lines
851 B
TypeScript

// @target: esnext
// @strict: true
type Two = { foo: { bar: true }, baz: true } | { [s: string]: string };
declare var u: Two
u.foo = 'bye'
u.baz = 'hi'
type Three = { foo: number } | { [s: string]: string } | { [s: string]: boolean };
declare var v: Three
v.foo = false
type Missing = { foo: number, bar: true } | { [s: string]: string } | { foo: boolean }
declare var m: Missing
m.foo = 'hi'
m.bar
type RO = { foo: number } | { readonly [s: string]: string }
declare var ro: RO
ro.foo = 'not allowed'
type Num = { '0': string } | { [n: number]: number }
declare var num: Num
num[0] = 1
num['0'] = 'ok'
const sym = Symbol()
type Both = { s: number, '0': number, [sym]: boolean } | { [n: number]: number, [s: string]: string | number }
declare var both: Both
both['s'] = 'ok'
both[0] = 1
both[1] = 0 // not ok
both[0] = 'not ok'
both[sym] = 'not ok'