0

Here's a type I'm working with:

type EmbeddingsSummary = { [path: string]: Embedding | WontGetEmbeddingReason }

WontGetEmbeddingReason is a string enum, so I expected that

(typeof embeddings[relativePath] === 'string') ? undefined :
    getCosineSimilarity(embeddings[relativePath], searchEmbedding)

will work fine (to be clear: Embedding is an array). However (with getCosineSimilarity expecting Embedding as the first argument), TypeScript complains:

Argument of type 'Embedding | WontGetEmbeddingReason' is not assignable to parameter of type 'Embedding'.

so in fact I'm currently using a mediocre workaround (casting):

(typeof embeddings[relativePath] === 'string') ? undefined :
    getCosineSimilarity(embeddings[relativePath] as Embedding, searchEmbedding)

Why TS doesn't deduce that if typeof embeddings[relativePath] === 'string' then embeddings[relativePath] is actually an Embedding? How can I fix this check?

YakovL
  • 7,557
  • 12
  • 62
  • 102
  • 1
    Try storing `embeddings[relativePath]` in a variable, so you aren't accessing it by key twice. TS is not great at narrowing dynamically-accessed properties like this. – kaya3 Feb 06 '23 at 14:03
  • Very similar issue [here](https://stackoverflow.com/q/50035288/12299000) - see the [second answer](https://stackoverflow.com/a/50035479/12299000). – kaya3 Feb 06 '23 at 14:05
  • @kaya3 thanks, this resolves the issue indeed. In fact, this may be something reasonable, as far as I remember JS may have custom getters that may have side-effects and hence the value may be different after second reading – YakovL Feb 06 '23 at 16:48

0 Answers0