Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
TypeScript lowercase string

Is there a way to make sure that TS will scream if it receives something else from lowercase string for fieldName?

type Props = {
  onEdit: (data: Record<string, string | number>) => void;
  title: string;
  fields: {
    fieldName: string;
    fieldValue?: string | number;
   }
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It's simple enough to create a utility to enforce that string literals are lowercase using the type utility Lowercase<StringType>:

TS Playground

type EnforceLowerCase<T extends string> = Lowercase<T> extends T ?
  string extends T ? never : T
  : never;
  
type Str1 = EnforceLowerCase<'Hello'>; // never
type Str2 = EnforceLowerCase<'hello'>; // "hello"

However, using it in your scenario would be very convoluted, because it would require using only string literals (which TS doesn't infer on object property values).


Instead, it's better to ensure conformance of the expectation at runtime. Here's an example using a pure function which doesn't mutate the input object:

TS Playground

function ensureLowerCaseFieldName (props: Props): Props {
  return {...props, fields: {
    ...props.fields,
    fieldName: props.fields.fieldName.toLocaleLowerCase(),
  }};
}

function doSomethingWithProps (props: Props) {
 props = ensureLowerCaseFieldName(props);
 console.log(props);
}

const props: Props = {
  onEdit: data => {},
  title: 'title',
  fields: {fieldName: 'Hello'},
};

doSomethingWithProps(props); // {..., fields: { fieldName: "hello" } }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda