Hello Typescript experts,
I'm looking for some advice on a TypeScript challenge I've come across.
My goal is to create a function that mimics the return type of Object.freeze, but with enhanced intellisense and type safety for the object being passed as a parameter. The objective is to have the inferred type for the group variable in the provided code snippet below be { id: "1" }
rather than { id: string }
, while also ensuring proper type checking for keys and values.
interface Group{
id: string;
}
const myFunction = (group: Partial<Group>) => group;
const group = myFunction({id: "1"})
// ^ typeof group = {id: "1"} and not {id:"string"}
Although using Object.freeze
provides the desired return type, there is no type-safety or intellisense for the object passed as a parameter.
const group = Object.freeze({id: "1"})
// ^ typeof group = {id: "1"} which is what I want
Is it possible to achieve this functionality in TypeScript?
Unfortunately, combining Object.freeze
with Partial
does not yield the correct return type:
const myFunction = (group: Partial<Group>) => Object.freeze(group)
const group = myFunction({id: "1"})
// ^ typeof group = {id: string} but I lack intellisense