Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function generic can infer type automatically, is there an equivalent for object generic type?

Tags:

typescript

function <Obj extends object>funName(o:Obj): Obj{
  ...
}

Function generic as above enforces a certain relationship between params and return types, without forcing the user to actually pass a type.

Is there an equivelant object generic type (POJO - plain old JS object), without forcing the user to pass a type?

type Props = <S extends string>{
  selectedTab: S 
  tabs: Record<S, any>
}

const props1: Props = { //ok 
  selectedTab: "about"
  tabs: {
    about: {...} 
  }
}

const props2: Props = { //Error
  selectedTab: "contact us"
  tabs: {
    about: {...} 
  }
}

I know this could be achieved by passing a type.

const props1: Props<"about"> = { 
  ...
}

But since automatic inference is possible for functions, perhaps it can also be used for objects.

like image 316
Ben Carp Avatar asked Oct 15 '25 05:10

Ben Carp


1 Answers

To achieve this kind of type inference for objects, you can use a combination of type inference and helper functions to create the object. This pattern is referred to as "type inference through function context."

type Props<S extends string> = {
  selectedTab: S;
  tabs: Record<S, any>;
};

function createProps<S extends string>(props: Props<S>): Props<S> {
  return props;
}

const props1 = createProps({
  selectedTab: "about",
  tabs: {
    about: { content: "About content" },
  },
}); // OK

const props2 = createProps({
  selectedTab: "contact us",
  tabs: {
    about: { content: "About content" },
  },
}); // Error: Type '"contact us"' is not assignable to type '"about"'.

TypeScript Playground

like image 165
Islam Y- Avatar answered Oct 18 '25 14:10

Islam Y-