why added delete keyword additional spec in typescript4.0 release spec?

168 views Asked by At

In this typescript v4.0, a new specification has been added for delete keyword.

[spec]

When using the delete operator in strictNullChecks, the operand must now be any, unknown, never, or be optional (in that it contains undefined in the type). 
Otherwise, use of the delete operator is an error.

I don't understand why this spec added.

Why can't delete specific type ?

I wonder why these specs were added.

I can turn off the "strictNullChecks" option, but that doesn't seem like a good idea.

Thank you.

--- edit ---
[example]

type UserFromDatabase = {
  name: string;
  password: string;
}

type User = Omit<UserFromDatabase, "password">


const signIn = (): User => {


  const userFromDatabase: UserFromDatabase = getUserFromDatabase();

  // do something
  // compare password ...

  delete userFromDatabase.password; // error occured typescript 4.0

  const user: User = { ...userFromDatabase };

  return user;
}


--- edit2 ---
typescript version : v4.0 [ new spec - delete keyword allow types ]

I know that javascript's delete keyword is deleting object's property not object.

Some object key is available when important logic.

So, after doing important logic, I want to delete object key.

2

There are 2 answers

5
Mu-Tsun Tsai On BEST ANSWER

If you could delete something, that means that something might not exist (especially after being deleted), so the type of that something has to allow non-existence. Consider the following example:

type T = {
    x: string;
}

let object: T = { x: "a" };
delete object.x;

// this is not supposed to make sense
console.log(object.x.toLowerCase());

In fact, the last line will throw an error in runtime. So it is the right thing to have stricter type check to prevent this kind of runtime error.

Update

So in your case you can do:

delete (userFromDatabase as any).password;
const user: User = userFromDatabase;

Or, as Aluan Haddad pointed out, a more clever way without using delete is:

let { password, ...user } = userFromDatabase;
return user;
0
aleung On

Cast to a Partial type to delete its property:

type UserFromDatabase = {
  name: string;
  password: string;
}

type User = Omit<UserFromDatabase, "password">

function deletePassword(user: UserFromDatabase): User {
  delete (user as Partial<UserFromDatabase>).password;
  return user;
}