代码之家  ›  专栏  ›  技术社区  ›  Sergey Rudenko

新手打字:可以是A型或B型。

  •  0
  • Sergey Rudenko  · 技术社区  · 6 年前

    我正在学习打字,我在这里搜索了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 }>
    }
    

    当我第一次从服务器接收数据时,它具有带字符串数组的数据形状,然后这个片段集对象获取图像URL及其数据形状更改。

    因此,如果我想要一个既适用于两者的类型,我将使用“any”:

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

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

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

    我很困惑,因为我肯定我看到了一些例子,人们使用“要么或”的方法来打印脚本,但我很难找到一个线索,知道什么时候(在实际意义上)可以,什么时候不应该使用它?

    现在,我坚持在应用程序中使用“any”,这很好,但我想更好地理解这个细微差别。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Alvaro Carrasco    6 年前

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

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