[英]Can you declare a object literal type that allows unknown properties in typescript?
Essentially I want to ensure that an object argument contains all of the required properties, but can contain any other properties it wants.基本上我想确保一个对象参数包含所有必需的属性,但可以包含它想要的任何其他属性。 For example:
例如:
function foo(bar: { baz: number }) : number {
return bar.baz;
}
foo({ baz: 1, other: 2 });
But this results in:但这导致:
Object literal may only specify known properties, and 'other' does not exist in type '{ baz: number; }'.
Yes, you can.是的你可以。 Try this:
尝试这个:
interface IBaz {
baz: number;
[key: string]: any;
}
function foo(bar: IBaz) : number {
return bar.baz;
}
foo({ baz: 1, other: 2 });
Well, i hate answering my own questions, but the other answers inspired a little thought... This works:好吧,我讨厌回答我自己的问题,但其他答案激发了我的一些思考......这有效:
function foo<T extends { baz: number }>(bar: T): void {
console.log(bar.baz);
}
foo({baz: 1, other: 2});
If the known fields are coming from a generic type the way to allow wildcards is with T & {[key: string]: unknown}
, any fields that are known must fit with the type's constraints and other fields are allowed (and considered type unknown
)如果已知字段来自通用类型,则允许使用通配符的方法是使用
T & {[key: string]: unknown}
,任何已知字段都必须符合类型的约束,并且允许其他字段(并被视为类型unknown
)
Here is a sample:这是一个示例:
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
Then if you have a generic type T
you can allow wildcard fields with WithWildCards<T>
然后,如果您有一个泛型类型
T
您可以使用WithWildCards<T>
允许通配符字段
This can be most easily accomplished by defining a type definition for the the function parameter.这可以通过为函数参数定义类型定义来最容易地实现。 Here's an example with inline type definition:
这是一个带有内联类型定义的示例:
function foo(bar: { baz: number }) : number {
return bar.baz;
}
const obj = { baz: 1, other: 2 };
foo(obj);
If you want to allow unknown properties for the entire object, you can use Record
如果要允许整个对象的未知属性,可以使用
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.