Nitish
Nitish

Reputation: 552

keyof is not working on 'name' property

I've declared an interface Student which has name and lastName property. After that, i created a KEY using keyof also declared a variable 'help' of type KEY.

Now I'm initializing variable 'help' with name then it's ok, but when initializing with lastName, I'm getting error Cannot find name 'lastName'.

interface Student { name: string; lastName: string; }

class Greeter {
    constructor() {}

  greeting(): void{
    type KEY = keyof Student;
    let help: KEY;

    help = name;   // ok
    help = lastName;  // Cannot find name 'lastName'
  }
}

Upvotes: 0

Views: 1660

Answers (1)

basarat
basarat

Reputation: 276225

Whats wrong with your code

name points to global name string : https://developer.mozilla.org/en-US/docs/Web/API/Window/name. Any string can be assigned to the help object.

FIX

Correct Example :

interface Student {
  name: string;
  lastName: string;
}
class Greeter {
  constructor() { }

  greeting(): void {
    type KEY = keyof Student;
    let help: KEY;

    help = 'name';   // ok
    help = 'lastName';  // ok
    help = 'asdf';  // ERROR
  }
}

Upvotes: 4

Related Questions