[英]Can you declare a object literal type that allows unknown properties in typescript?
基本上我想確保一個對象參數包含所有必需的屬性,但可以包含它想要的任何其他屬性。 例如:
function foo(bar: { baz: number }) : number {
return bar.baz;
}
foo({ baz: 1, other: 2 });
但這導致:
Object literal may only specify known properties, and 'other' does not exist in type '{ baz: number; }'.
是的你可以。 嘗試這個:
interface IBaz {
baz: number;
[key: string]: any;
}
function foo(bar: IBaz) : number {
return bar.baz;
}
foo({ baz: 1, other: 2 });
好吧,我討厭回答我自己的問題,但其他答案激發了我的一些思考......這有效:
function foo<T extends { baz: number }>(bar: T): void {
console.log(bar.baz);
}
foo({baz: 1, other: 2});
如果已知字段來自通用類型,則允許使用通配符的方法是使用T & {[key: string]: unknown}
,任何已知字段都必須符合類型的約束,並且允許其他字段(並被視為類型unknown
)
這是一個示例:
type WithWildcards<T> = T & { [key: string]: unknown };
function test(foo: WithWildcards<{baz: number}>) {}
test({ baz: 1 }); // works
test({ baz: 1, other: 4 }); // works
test({ baz: '', other: 4 }); // fails since baz isn't a number
然后,如果您有一個泛型類型T
您可以使用WithWildCards<T>
允許通配符字段
這可以通過為函數參數定義類型定義來最容易地實現。 這是一個帶有內聯類型定義的示例:
function foo(bar: { baz: number }) : number {
return bar.baz;
}
const obj = { baz: 1, other: 2 };
foo(obj);
如果要允許整個對象的未知屬性,可以使用Record
function doStuff(payload: Record<string|number, unknown>): Record<string|number, unknown> {
return { anyProp: 'anyValue' }
}
當使用unknown
類型時,您可以使用narrowing
的概念來檢查您希望從您正在經歷的值中獲得的類型,並根據您的需要操作這些值,例如
const messages: string []=Object.values(obj).map(val: unknown=>typeof obj==='object'?obj!['message']:obj)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.