Andrii Yakymyshyn
Andrii Yakymyshyn

Reputation: 228

TypeScript: Property 'propertyName' does not exist on type 'T'

Currently I'm learning TypeScript, and I have an issue: "Property 'value' does not exist on type 'T'"

Here's my code:

type ParseType = <T>(value: T, opts: any, useRounding: boolean) => number;
const parse: ParseType = function(value, opts: any, useRounding): number {
//...
if (isNumber || value instanceof currency) {
  v = (isNumber ? value : value.value) * precision;
}
//...

I will be really grateful for help :)

UPD: I just added new interface interface Currency {value?: number;}, made my generic type extend it: type ParseType = <T extends Currency>(value: T, opts: any, useRounding: boolean) => number;, and wrote two separate conditions as was suggested in comments.

Upvotes: 0

Views: 875

Answers (1)

Johannes Reuter
Johannes Reuter

Reputation: 3547

I'm guessing currency always contains a value prop? Typescript can't infer this because you are using two nested conditional statements - it could in theory but it's not clever enough. In the inner ternary condition Typescript doesn't know about the fact that !isNumber also means instanceof currency - this connection is lost. The same happens for isNumber - even if you got this boolean by checking whether value is a number at some point, this type-infering property won't carry along if you are using it somewhere else in a conditional. For Typescript to infer types, the check has to happen right there in the condition.

Try this (flattening the nested conditions into two separate ones):

if (typeof value === 'number') {
  v = value * precision;
} else if (value instanceof currency) {
  v = value.value * precision;
}

A condensed example:

function abc<R>(v: R) {
  if (typeof v === 'number') {
    // Typescript knows v is a number
  }

  const isNumber = typeof v === 'number';
  if (isNumber) {
    // Typescript knows nothing about v
  }
}

Upvotes: 1

Related Questions