Skip to content

Set a type guard for hasOwnProperty signature.  #18282

Closed
@ezequiel-umu

Description

@ezequiel-umu

TypeScript Version: 2.5.0-dev.20170629

Watch this code with a new version of hasOwnProperty:

function hasOwnProperty<T, K extends keyof T>(object: T, key: string): key is K {
  return object.hasOwnProperty(key);
}

const x = {
  a: "a",
  b: "b",
};

// Ensure k is unknown for the transpiler:
const k = String.fromCharCode("a".charCodeAt(0) + 1);

// This is working without any problem.
if (hasOwnProperty(x, k)) {
  x[k] = "anything";
}

// This blames: file: 'Element implicitly has an 'any' type because type '{ a: string; b: string; }' has no index 
if (x.hasOwnProperty(k)) {
  x[k] = "anything";
}

// This emits the same error:
if (k in x) {
  x[k] = "anything";
}

Suggestion:

Change the actual declaration of hasOwnProperty:

hasOwnProperty(v: PropertyKey): boolean;

With a new one type guarded:

hasOwnProperty<T, K extends keyof T>(this: T, key: string): key is K;

Something that also could be added is a type guard to in operator to work as the type guard of the suggested hasOwnProperty .

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionDomain: lib.d.tsThe issue relates to the different libraries shipped with TypeScriptSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions