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

155
Visualizações
typescript infer prop type from type of other property
interface featureType<Props=any, State=any> {
  initialState: State;
  props: Props;
  processState: (props: Props, state: State) => any;
}

const feature1Comp: featureType = {
  initialState: { lastName: '' },
  props: { firstName: 'eliav' },
  processState: (props, state) => {
    props; // type should be {firstName: string} but instead is any
  },
};

why props type is not being inferred? what am I missing?

quick playground here(the URL is being cut so copy-paste the code)

(I post this question only because it takes too much time to find a solution for that issue and this is quite a common usage for typescript)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  1. Capitalize your types and interfaces (FeatureType) - that's a convention
  2. If you use generics, you should provide them to your type definiton:

const feature1Comp = FeatureType<{ firstName: string}, any>

Treat generics as a kind of 'type functions'. If you don't provide the concrete types, defaults will be used, so TS assumes Props and State are typed as any.

Update: here is what will work with infering

interface Component<P,S> {
    initialState: S,
    props: P,
    processState: (props: P, state: S) => any
}

function createComponent<P, S>(arg: Component<P, S>): Component<P, S> {
    return arg;
}

const x = createComponent({
    initialState: 'someValue',
    props: { firstName: 'Elias' },
    processState: (p, s) => {
        console.log(p.firstName) // Works
        console.log(p.lastName) // Error
    }
})
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