Search code examples
typescripttsc

How to tell compiler that this variable is not a primitive value?


I want to declare that my function's args are object.

function foo(obj1: object, obj2: object){
  obj1.name = 'foo'
  obj2[MAYBE_ANY_PROPERTIES] = 'bar'
}

But when I try to compile, tsc tell that Property 'name' does not exist on type '{}'.

I understand this error, but anyway, I want to tell compiler that obj1 is an object which may have any properties, but it should never be a primitive value. How can I do?


Solution

  • If you want the object to be indexable, you need a string index. You can use the Record type to get that effect:

    function foo(obj1: Record<string, any>, obj2: Record<string, any>){
      obj1.name = 'foo'
    }
    
    foo(1, 2) //err
    foo("", "") // err
    
    foo({ name: "" }, { name: "" }) // ok
    

    You might consider a stricter type if your objects must contain a specific property:

    function foo(obj1: {name: string } & Record<string, any>, obj2: {name: string } & Record<string, any>) {
      obj1.name = 'foo'
    }
    
    foo({ name: "" }, { name_: "" }) // error no name