1

I have the current scenario.

type A = { b: string, c: number }

an object that I'll consume from an API , that will give me either

A[] || []

Currently, if I try to use it,

const apiData: A[] || []
const b = apiData[0].a // this I wanted it to error, but it doesn't.

How do I model in a way where this will error ?

1
  • const b = apiData[0].a definitely does error. Also you have a typo, its A[] | [], not A[] || [] Commented Jun 9, 2021 at 12:31

1 Answer 1

1

I believe the simplest solution here is Partial:

type A = { b: string, c: number }

type Obj = Partial<A[]>
declare var apiData: Obj;

const check = apiData[0] // A | undefined

OR you can use typeguard

type A = { b: string, c: number }

type Obj = A[]
declare var apiData: Obj;

const isEmpty = <Elem,>(arg: Elem[]): arg is never[] => arg.length === 0

if (isEmpty(apiData)) {
  const x = apiData[0] // never
} else {
  const x = apiData[0] // A
}

Next type

type Obj = A[] | never[]

does not work as you might expect because never[] extends A[]

type IsAssignable = never[] extends A[] ? true : false // true

Also, you can use noUncheckedIndexedAccess flag

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.