简体   繁体   English

从数组值推断类型

[英]Infer type from array value

Using Typescript 3.8.3.使用 Typescript 3.8.3。

I'm trying to set up types for the following data, but cannot for the life of me figure it out.我正在尝试为以下数据设置类型,但我一生都无法弄清楚。

type Info = {
  title: string;
  description: string;
    items: Array<Item<object>>;
}

type Item<T> = {
  title: string;
  data: T;
}

const info: Info = {
  title: 'some title',
  description: 'some description',
  items: [
    { title: 'title1', data: { param1: 'something', param2: 'something else' } },
    { title: 'title2', data: { param3: 'abc' } },
    { title: 'title3', data: { param1: 'not the same as above, just the key name', param4: 123 } }
  ]
};

info.items[0].data.param1 // Property 'param1' does not exist on type 'object'

I know Array<Item<object>> is wrong, but I can't figure out how I can infer type of the union of an array of elements.我知道Array<Item<object>>是错误的,但我不知道如何推断元素数组的联合类型。

Is what I want to achieve even possible?我想要实现的目标是否可能?

The only thing you can do is:你唯一能做的就是:

type Info = {
  title: string;
  description: string;
    items: ReadonlyArray<Item<object>>; // Only work with ReadonlyArray
}

type Item<T> = {
  title: string;
  data: T;
}

const info = {
  title: 'some title',
  description: 'some description',
  items: [
    { title: 'title1', data: { param1: 'something', param2: 'something else' } },
    { title: 'title2', data: { param3: 'abc' } },
    { title: 'title3', data: { param1: 'not the same as above, just the key name', param4: 123 } }
  ]
} as const;

info.items[0].data.param1 // 'something' as info type is known
const anotherInfo: Info = info // info const be assigned to Info

If info is not 'const' type, you can modify it like: info.items = [] , so typescript cannot guarantee the value / type of info.items[0].data.param1如果info不是 'const' 类型,您可以将其修改为: info.items = [] ,因此 typescript 无法保证info.items[0].data.param1的值/类型

Would this work?这行得通吗?

type Info<T> = {
  title: string;
  description: string;
  items: Item<T>[];
}

type Item<T> = {
  title: string;
  data: T;
}

const info = {
  title: 'some title',
  description: 'some description',
  items: [
    { title: 'title1', data: { param1: 'something', param2: 'something else' } },
    { title: 'title2', data: { param3: 'abc' } },
    { title: 'title3', data: { param1: 'not the same as above, just the key name', param4: 123 } }
  ]
};

info.items[0].data.param1 // string | undefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM