Can you declare a object literal type that allows unknown properties in typescript?

前端 未结 4 1550
[愿得一人]
[愿得一人] 2020-12-20 12:16

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:

fu         


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-20 13:05

    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)

    Here is a sample:

    type WithWildcards = 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

提交回复
热议问题