代码之家  ›  专栏  ›  技术社区  ›  Sharon

在Javascript/TypeScript中,有没有一种方法可以区分不同接口类型的对象?

  •  0
  • Sharon  · 技术社区  · 3 年前

    LocalUser {
      data {
        value: LocalDataValue
      },
      ...various other methods etc...
    }
    RemoteUser {
      data {
        value: RemoteDataValue
      },
      ...various other methods etc...
    }
    

    然后它给了我一个这样定义的用户(我可以根据它是如何获得的来确定它是哪种类型的用户,但似乎没有一种方法可以实际传递这些信息):

    User {
      value: LocalUser|RemoteUser
    }
    

    LocalUser ,因为我只想在上执行特定操作 LocalUsers 本地用户 是一个 RemoteUser 或者

    我在文档中找不到任何地方可以告诉我它们之间的区别,尽管我知道有些方法只出现在屏幕上 本地用户 远程用户 (如我能行 localUser.enable() 但是 remoteUser.enable() 不起作用)。

    if(myUnknownUser isInstanceOf (LocalUser)) { doSomething() }
    

    还是更好的处理方法?

    1 回复  |  直到 3 年前
        1
  •  1
  •   captain-yossarian from Ukraine    3 年前

    typeguards

    考虑这个例子:

    
    type LocalUser = {
      tag: 'LocalUser';
      name: 'John'
    }
    
    type RemoteUser = {
      tag: 'RemoteUser';
      name: 'David'
    }
    type User = LocalUser | RemoteUser
    
    // typeguard
    const isLocal = (user: User): user is LocalUser => user.tag === 'LocalUser'
    
    // typeguard
    const isRemote = (user: User): user is RemoteUser => user.tag === 'RemoteUser'
    
    declare var user: User;
    
    if (isLocal(user)) {
      const x = user // LocalUser
    }
    
    if (isRemote(user)) {
      const x = user // RemoteUser
    }
    
    

    如何实现typeguard取决于您