【问题标题】:keyof is not working on 'name' propertykeyof 不适用于“名称”属性
【发布时间】:2018-01-11 13:22:46
【问题描述】:

我已经声明了一个具有 name 和 lastName 属性的接口 Student。之后,我使用 keyof 创建了一个 KEY,还声明了一个 KEY 类型的变量“帮助”。

现在我用 name 初始化变量 'help' 然后没问题,但是当用 lastName 初始化时,我收到错误 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'
  }
}

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    你的代码有什么问题

    name 指向全局 name 字符串:https://developer.mozilla.org/en-US/docs/Web/API/Window/name。任何string 都可以分配给help 对象。

    修复

    正确的例子:

    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
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 2010-10-25
      • 2022-07-23
      相关资源
      最近更新 更多