新手打字稿:可以是typeA或typeB情况

时间:2018-07-28 16:16:38

标签: typescript

我正在学习打字稿,我确实在SO / Google中搜索了有关我的问题的详细说明,但是我没有找到满意的答案(或者我还不明白这里的含义是什么:https://www.typescriptlang.org/docs/handbook/advanced-types.html

我的简单示例是,我有一个接口,其属性最初可以是字符串,然后该接口更改为具有其他类型(从字符串到对象)。

这就是发生的事情:

export interface SnippetSetReceivedFromServer {
    title: string,
    snippets: Array<string>
}

export interface SnippetSetTransformedByClient {
    title: string,
    snippets: Array<{ _id: string, sanitizedLocalThumbnail: SafeUrl }>
}

我第一次从服务器接收数据时,它具有带有字符串数组的数据形状,然后此代码段集对象获取了图像网址,并且其数据形状发生了变化。

因此,如果我只想拥有一种适用于两者的类型,则可以使用“ any”:

export interface GenericSnippetSet {
    title: string,
    snippets: Array<any>
}

但是为什么我不能使用这种方法:

export interface SnippetSet {
    title: string,
    expanded?: boolean,
    snippets: Array<string | { _id: string, sanitizedLocalThumbnail: SafeUrl }>
}

我很困惑,因为我确定我看到人们在打字稿上使用“要么或”方法的示例,但是我很难找到何时(在实际意义上)可以使用以及何时不应该使用的线索?

目前,我坚持在应用程序中使用“任何”功能,但我想更好地理解这一细微差别。

1 个答案:

答案 0 :(得分:1)

您通常希望禁止使用无效的值。您的版本将允许使用无效值。您可能会考虑这种方法:

export interface SnippetSet<T> {
  title: string,
  expanded?: boolean,
  snippets: Array<T>
}

您现在可以在呼叫站点或通过别名进行参数化了:

type GenericSnippetSet = SnippetSet<string>
type SnippetTransformed = SnippetSet<{ _id: string, ... }>

编辑:联合类型的一个很好的用途是,任何版本的联合都是有效的,并且您打算通过一些条件代码(可能是switch语句)在运行时处理所有版本。

相关问题