1

OI have gotten two values from api, one is fruit and another is vegetable. I only know both type are string, but not the exactly values.

// fruit can be any string, not apple only, same on vegetable. I don't know what exactly value api return.
const fruit: string = 'apple'
const vegetable: string = 'onion'

I want to define a type Food, which can contain the substring fruit and vegetable. As I don't know the return value from api, I cannot define a type like

type Fruit =  'apple' | 'banana'
const fruit: Fruit = 'apple

I know in this way, it's working. But my one is not Fruit, it's only string.

This is what I tried

type Fruit = typeof fruit
type Vegetable = typeof vegetable
type Food = `${Fruit} ${Vegetable} ${string}`

In this way, the type is {string} {string} {string}, the first two is not the exacly value from fruit and vegetable. The below is what I want

const test1: Food = 'a b c d'; // wrong
const test2: Food = 'apple onion c d'; // pass

How can I define that Food type if I cannot have a union type for the value, only can be a generic string type?

1 Answer 1

1

This is not possible.

The type system only works at compile time. That means that before your code ever runs. But a value from an external API wont exist until runtime. When you app is running there is no type system.

That means that if an API is typed to return string, that's the most you can know about it.

The closest thing you can do is a type predicate:

function hasApple(input: string): input is `${string}apple${string}` {
  return input.includes('apple')
}

const bad: `${string}apple${string}` = input // error

if (hasApple(input)) {
    const good: `${string}apple${string}` = input // works
}

But then you have to know exactly what you are looking for. So unless you know what strings could be returned, this won't help much.

The most specific a type of a runtime value can be is all the possibilities of that that runtime value.

Sign up to request clarification or add additional context in comments.

Comments

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.