简体   繁体   English

你能声明一个允许在打字稿中使用未知属性的对象文字类型吗?

[英]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.

相关问题 如何将类的属性作为对象文字类型获取? - How do I get the properties of a class as object literal type? TypeScript泛型:泛型函数类型和对象文字类型的调用签名不相等(类型&#39;T&#39;不能分配给类型&#39;T&#39;) - TypeScript generics: Inequivalence of generic function type and call signature of an object literal type (Type 'T' is not assignable to type 'T') 如何在Typescript中获得泛型类型的属性 - How do you get the properties of a generic type in Typescript TypeScript 类型将 object 类型的某些属性动态标记为“必需”和“已定义”? - TypeScript type to dynamically mark certain properties of an object type as “required” and “defined”? 您可以声明可变长度的泛型类型声明吗? - Can you declare a variable length Generics type declaration? TypeScript:推断已定义类型的文字类型 - TypeScript: Infer literal type of already defined type TypeScript:为在通用对象上评估函数属性的函数推断正确的类型 - TypeScript: Inferring the correct type for a function that evaluates function properties on a generic object 使用随机数组字符串键入 object 键/属性 - TypeScript - Using random array strings to type object keys/properties - TypeScript TypeScript 可以将 keyof 限制为特定类型的属性列表吗? - can TypeScript restrict keyof to a list of properties of a particular type? 如何在 typescript 中为文字名称编写泛型类型? - How to write generic type for literal name in typescript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM