#I sill confused on this narrowing...

9 messages · Page 1 of 1 (latest)

wide isle
#
image: ImageProps | NonNullable<ReactElement>;

type ImageProps = Omit<JSX.IntrinsicElements['img'], 'src' | 'srcSet' | 'ref' | 'alt' | 'width' | 'height' | 'loading'> & {
    src: string | StaticImport;
    alt: string;
    width?: number | `${number}`;
    height?: number | `${number}`;
  ...
}

{image.src ? (
          <Image
            {...{
              ...image,
              className: "z-10 h-full object-cover w-full",
            }}
          />
        ) : image}

Why does image.src give me a error line?

I would imagine that this scenario is a clear cut case. That ReactElement doesn't have a key of src, so the presence of a src in the object image would have to be a type of ImageProps. If it didnt have a source it would be an React element. What am I missing here or have i misunderstood this type of narrowing?

#

This is the ts error i receive

Property 'src' does not exist on type 'ReactElement<any, string | JSXElementConstructor<any>> | ImageProps'.
Property 'src' does not exist on type 'ReactElement<any, string | JSXElementConstructor<any>>'.

wide isle
#

I had to create type predicate but still wondering why it didn't work as I intended before.

broken coral
#

This Omit statement removes src, alt, and other attributes from the img element.

#

const { src, alt, ...rest } = props;
<img src={src} alt={alt} {...rest}/>

lyric willow
dusk barnBOT
#
type AOrB = { 
  a: string
} | { 
  b: string
}

declare const x: AOrB;
if(x.a) {
//   ^
// Property 'a' does not exist on type 'AOrB'.
//   Property 'a' does not exist on type '{ b: string; }'.
  
}
lyric willow
#

You have to narrow the union before trying to access a property that's exclusive to a specific branch of the union.

#

It's best to narrow with something like typeof or a discriminated union, but in can be used too and is the smallest "fix" here: