索引访问运算符奇怪的语法

Pet*_*nko 0 typescript

考虑以下导致 TS 编译器错误的代码:

interface Car {
  manufacturer: string;
  model: string;
}

let taxi: Car = {
  manufacturer: 'Toyota',
  model: 'Camry',
};

// this code returns an error. why??
function getProperty<T, K extends keyof T>(o: T, propertyName: K): K {
  return o[propertyName];
}

let makeAndModel: string[] = getProperty(taxi, 'model');
Run Code Online (Sandbox Code Playgroud)

T是任意类型,并且K extends keyof T(即 K 必须是T键之一,在我们的例子中它可以是manufacturermodel)。在函数返回类型中,我们声明K为我们的返回类型,因此我们已经告诉编译器:“嘿,这个函数只能返回类型 ( K) 的变量,该变量必须是出租车 ( T) 键 ( manufacturer, model) 之一。

就是这样。这就是编译器应该知道的全部内容。我们已经限制K为其中一T键。为什么那么我们需要在此处K添加额外的内容[]

// this code works. why??
function getProperty<T, K extends keyof T>(o: T, propertyName: K): [K] { // additional []. any reason?
  return o[propertyName];
}
Run Code Online (Sandbox Code Playgroud)

Ale*_* L. 5

返回类型错误。您正在返回值,而不是键,所以它应该是:

function getProperty<T, K extends keyof T>(o: T, propertyName: K): T[K] {
    return o[propertyName];
}
Run Code Online (Sandbox Code Playgroud)

操场