我通常在 JavaScript 中執行此操作:
function setArbitraryProperty(object, field, value) {
object[field] = value;
}
現在我如何在 TypeScript 中做到這一點?
function setArbitraryPropertyTS(object: MyXType, field: string, value: unknown): void {
object[field] = value;
}
我得到:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'MyXType'.
No index signature with a parameter of type 'string' was found on type 'MyXType'.
如果我嘗試使用keyof:
function setArbitraryPropertyTS(object: MyXType, field: keyof MyXType, value: unknown): void {
object[field] = value;
}
我得到:
Type 'unknown' is not assignable to type 'never'.
我怎樣才能讓它作業?我只想創建一個通用函式,它在型別化物件上設定任意屬性,其中“任意屬性”是在物件上明確定義的屬性。所以我基本上想這樣使用它:
type MyXType = {
a: string;
b: number;
c: boolean;
}
const obj1 = { a: 'foo', b: 123, c: true };
setArbitraryPropertyTS(obj1, 'a', 'bar');
就我而言,mysetArbitraryPropertyTS實際上是一個非常復雜的函式,它做了很多事情,最后更新了屬性,我想根據我設定的屬性以多種不同的方式改變邏輯。所以我可能有:
setArbitraryPropertyTS(obj: MyXType, field: keyof MyXType, val: unknown): void {
// complex logic...
obj[field] = val;
}
setA(obj: MyXType): void {
// complex logic...
const val = 'foo' // retrieved from logic...
setArbitraryPropertyTS(obj, 'a', val);
}
setB(obj: MyXType): void {
// complex logic...
const val = 123 // retrieved from logic...
setArbitraryPropertyTS(obj, 'b', val);
}
setC(obj: MyXType): void {
// complex logic...
const val = true // retrieved from logic...
setArbitraryPropertyTS(obj, 'c', val);
}
這有什么可能嗎?
uj5u.com熱心網友回復:
你需要泛型。將物件宣告為泛型型別,將欄位宣告為作為物件型別鍵的另一個欄位,并將值宣告為可分配給物件的該鍵的東西。
function setArbitraryPropertyTS<
T extends object,
F extends keyof T,
V extends T[F]
>(
object: T,
field: F,
value: V
) {
object[field] = value;
}
const obj1 = { a: 'foo', b: 123, c: true };
setArbitraryPropertyTS(obj1, 'a', 'bar');
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/482440.html
標籤:打字稿
