0

How can I get expected result and what's the best approach to limit property when type casting ??

interface user {
  name: string
  password: string
}

interface userEntity {
  name: string
}

const user: user = {
  name: 'name',
  password: 'password'
}

const result = user as userEntity;
// output { name: 'name', password: 'password' }
// expected { name: 'name' }
Tung Tse
  • 347
  • 1
  • 3
  • 9
  • What the real case here? Force casting is not good practice. And even if it was ok, what is the difference between the "user entity" and the "user"? Please give a more real-life scenario – MCMatan Mar 24 '19 at 17:24
  • the user is a model get from database ORM, then I wanna response to frontend exclude password. Actually, I can new a variable exclude password for the response, but I don't think it is a good approach. – Tung Tse Mar 24 '19 at 18:51
  • It sounds like a better approach to me. As a rule of thumb, any time you are force casting, you probably are doing something wrong. You can have a dedicated constructor that accepts User input – MCMatan Mar 24 '19 at 18:54

1 Answers1

2

Type casting has no effect at runtime, the values in object will remain the same. Type casting only purpose is to suppress compilation errors when type-checking, when you know better than the compiler what the actual type of the object should be.

To copy only a subset of properties when assigning a value to another object, you have to do it explicitly at runtime. There is a multitude of possible ways to do that, for example

const result: userEntity = {name: user.name};
artem
  • 46,476
  • 8
  • 74
  • 78