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

前端 未结 4 1538
[愿得一人]
[愿得一人] 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 12:50

    This can be most easily accomplished by defining your object before the function call:

    function foo(bar: { baz: number }) : number {
        return bar.baz;
    }
    
    const obj = { baz: 1, other: 2 };
    
    foo(obj);
    
    0 讨论(0)
  • 2020-12-20 12:52

    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 });
    
    0 讨论(0)
  • 2020-12-20 13:02

    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});
    
    0 讨论(0)
  • 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> = 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>

    0 讨论(0)
提交回复
热议问题