Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
Generate a const typed object in TypeScript

I am trying to generate a const typed object by passing in a string I want to use as the type, is this possible, I have tried the below and it's bringing out the wrong type.

const test = <T> (name: T) => {
  const hi: { name: T } = {
    name
  } as const
  return hi
}

const test1 = test('hello')

I'd like this to be of type

{
    name: 'hello';
}

But instead it's of type

{
    name: string;
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

In order to infer literal type of an argument, usually you need to add appropriate constraint to your generic argument. See this example:

function test<T extends string>(name: T) {
  return { name };
}

const test1 = test('hello') // {name:"hello"}

If you are interested in more examples, you can check my article

If you want to add some validation, you can use conditional type:

// Forbids using underscore as a prefix
type IsAllowed<T extends string> = T extends `_${string}` ? never : T

function foo<T extends string>(name: IsAllowed<T>) {
  return { name };
}


const test1 = foo('hello') // ok 
const test2 = foo('_hello') // expected error

Or you may use this utility type :

type IsLiteral<T extends string> = T extends string ? string extends T ? never : T : never

function test<T extends string>(name: IsLiteral<T>) {
  return { name };
}

If you want to allow only string literals

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!