打字稿道具可以是字符串数组或具有特定键值的对象数组

时间:2019-05-05 15:56:09

标签: javascript typescript

我有一个 prop ,它可以是图像字符串 URL 的数组,也可以是具有一些key-value对的对象数组,其中一些{{ 1}}对是必需的,有些是可选的。

如何设置类型,以便验证自己是否得到了其中一个

key-value

我尝试过,但是没有用!

道具interface Image { url: string; thumbnail?: string; } export class Props { public image: string[] | Image[] = []; } 可以是:

image

['url_1', 'url_2', '...']

2 个答案:

答案 0 :(得分:0)

请尝试以下操作:

  • 任何接口的实际名称前均使用“ I”开头。它被用作最佳实践。
interface IImage {
    url: Object[],
    // This can get data in key-value pairs as below format:
      //  [{ 'url': 'https://www.google.com', 'url': 'https://www.twitter.com' }]
    thumbnail ?: string[]
}

interface IImage2 {
    url: string[],
    // This can get data as below format:
      // ['https://www.google.com', 'https://www.twitter.com' ..]
    thumbnail ?: string[]
}

export class Props {
    image: IImage;
    image2: IImage2;
}

答案 1 :(得分:0)

您可以简单地做到这一点:

interface Image {
  url: string[],
  thumbnail?: []
}

export class Props {
  public image: Image;
}
相关问题