Whenever I utilize the delete
operator in Typescript, it appears that the system does not recognize that the property has been eliminated. For instance:
interface HasName {
name: string;
}
interface HasNoName {
name: never;
}
function removeName(
input: HasName,
): HasNoName {
const output = {...input};
delete output.name;
return output; // This results in an error
}
Typescript disapproves of the function with the following error message:
Type '{ name: string; }' is not compatible with type 'HasNoName'.
Properties of 'name' are not matching.
String cannot be assigned to 'never'.
In my view, upon removing the name
property, Typescript should interpret output
as being compliant with HasNoName
, but this does not seem to be the case.
I can easily find a workaround, such as
const nameless = output as HasNoName; return nameless
. However, I am curious to understand WHY this error occurs and whether it is intentional or a bug?