Как я могу сохранить разрешение типа объединяющего типа внутри инициализатора индексированного типа? - PullRequest
0 голосов
/ 08 апреля 2020
// basic types
type One = { name: string; };
type Many = Array<One>;
type OneOrMany = One | Many;

// testing resolution of the OneOrMany type based on contents
var one: OneOrMany = { name: "sam" };
one.name = "pat"
// ts correctly infers that one is a One that has .name
var many: OneOrMany = [{ name: "sam" },{ name: "ash" }];
many[0].name = "pat"
many.map(x => x)
// ts correctly infers that many is a Many, an array I can index or .map()
// all is well

// testing resolution of the OneOrMany type within an index type
interface OOMDict { [key: string]: OneOrMany; }
var oomdict2: OOMDict = {};
oomdict2.one = { name: "sam" };
oomdict2.one.name = "pat";
oomdict2.many = [{ name: "sam" }, { name: "ash" }];
oomdict2.many[0].name = "pat";
// all is well

// testing resolution within an index type initializer
var oomdict: OOMDict = { one: { name: "sam" }, many: [{ name: "sam" }, { name: "ash" }] };
oomdict.one.name = "pat";
// ERROR: Property 'name' does not exist on type 'OneOrMany'.
// ERROR: Property 'name' does not exist on type 'Many'.(2339)
oomdict.many[0].name = "pat";
// ERROR: Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'OneOrMany'.
// ERROR: Property '0' does not exist on type 'OneOrMany'.(7053)

Почему это работает везде, кроме случаев, когда я инициализирую OOMDict? Содержимое oomdict и oomdict2 идентично (до заданий, являющихся предметом теста).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...