假設我有以下 JS 函式:
function extractProperty(propName) {
return x => x[propName];
}
我可以extractProperty通過 Typescript 的型別推斷鍵入 st 我得到以下資訊:
const x = { first: 1, second: "two" };
const y = { first: [1], second: 2 };
// or any other object having first and second
const a1 = extractProperty("first")(x); // a1 should be of type number
const a2 = extractProperty("second")(x); // a2 should be string
const a3 = extractProperty("first")(y); // a3 should be number[]
const a4 = extractProperty("second")(y); // a4 should be number
const getFirst = extractProperty("first");
// getFirst should be <T> (t: T) => T["first"]
const getSecond = extractProperty("second");
// getSecond should be <T> (t: T) => T["second"]
如果不是引數propName,我有一個固定的屬性名稱,我可能會執行以下操作:
function extractPropertyFirst ():
<TFirst> (x: { first: TFirst }) => TFirst
或者,稍微朝著我想要實作的方向發展,
function extractPropertyFirst ():
<T> (x: T) => T["first"]
然而,我怎樣才能讓打字稿把函式的引數作為屬性名呢?
我玩過以下方法,但沒有成功:
function getProperty<K> (propName: K):
<TProp> (t: { [K]: TProp }) => TProp {
return x => x[propName];
}
Typescript 不接受一般K作為索引型別。
uj5u.com熱心網友回復:
您可以getProperty通過使用{[Key in K]: TProp}或等效地Record<K, TProp>為 的型別t添加K extends PropertyKey約束來完成作業:
function extractProperty<K extends PropertyKey>( propName: K):
<TProp>(t: Record<K, TProp>) => TProp {
return (x) => x[propName];
}
const a1 = extractProperty("first")(x);
// type: number
const a2 = extractProperty("second")(x)
// type: string
const a3 = extractProperty("first")(y);
// type: number[]
const a4 = extractProperty("second")(y);
// type: number
TypeScript 游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/462367.html
標籤:打字稿
