0
let adminList = origData.map((data) => { return data as adminPermission.AdminUser })
export interface AdminUser {
  uid: string
  displayName: string
  email: string
  emailVerified: boolean
  isAnonymous: boolean
  photoURL: string
}

I want to reformat my data same with the structure of 'AdminUser' interface. But after typecase " ~ as ~ ", the result is exactly the same as before.

So, I just had to make a longer code.

  1. Casting doesn't work, so I changed the way to define a class.
let adminList = origData.map((data) => {
  let newData = new adminPermission.AdminUser(data)
  return newData
})
  1. Defined new Class
export class AdminUser {
  constructor(object: any) {
    this.uid = object.uid
    this.displayName = object.displayName
    this.email = object.email
    this.emailVerified = object.emailVerified
    this.isAnonymous = object.isAnonymous
    this.photoURL = object.photoURL
  }
}

It works, but it is not what I expected in Typescript usage. And totally useless and messy code.

How can I reselect object member using an Interface?

Fredric Cliver
  • 175
  • 1
  • 1
  • 9
  • *"Casting doesn't work"* -- JavaScript and TypeScript do not support casting. `data as adminPermission.AdminUser` is called [type assertion](https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions) and it doesn't do anything to the code. It just tells the TS compiler: _"don't complain, I know what I'm doing"._ – axiac Sep 17 '20 at 14:27
  • @axiac Oh, thank you. I've searched about type assertion now. So I understood! But, is there any good way in my case? – Fredric Cliver Sep 17 '20 at 14:43
  • Can you explain your use case more or provide a [mcve] so I can demonstrate the issue to myself? If `origData` has all the same properties as `AdminUser`, then it *is* an `AdminUser` and you don't need to do anything to it (other than possibly use a type assertion to tell the compiler that `origData`'s elements are `AdminUser`s). What, specifically, goes wrong if you just use your type assertion version? A [mcve] that someone can just drop into a standalone IDE like [The TypeScript Playground](https://www.typescriptlang.org/play) would help others point you to a solution. – jcalz Sep 17 '20 at 15:39
  • @jcalz Really thank you for advise me about reproducible example. (https://gist.github.com/fredriccliver/e6cdec5fff401bf8de295b6ef545b842) here is a sample code! – Fredric Cliver Sep 18 '20 at 03:42
  • Ah, this question has been asked before. Let me link to the other questions with their answers. You have to do some kind of runtime work to get this to happen. – jcalz Sep 18 '20 at 14:04

0 Answers0