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?

3
  • 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. Commented Feb 6, 2023 at 14:03
  • Very similar issue here - see the second answer. Commented Feb 6, 2023 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 Commented Feb 6, 2023 at 16:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.