Nick Settje
Nick Settje

Reputation: 3332

ReactXP: "'length' is missing in type" for array of interface

I am using ReactXP (which uses TypeScript) to code a chat client that displays a single panel that contains a stack of messages in the top part and a form at the bottom in which to submit new chat messages. I am trying to break the stack of messages into an array of objects of ChatMessage type. This particular example uses the ReactXP extension for VirtualListView.

When I try to compile the example below, I receive the following error:

TS2322: Type '{ messages: ChatMessage[]; }' is not assignable to type 'ChatMessage[]'.
   Property 'length' is missing in type '{ messages: ChatMessage[]; }

I can see from the error message that ChatMessage[] is not being interpreted as an array because it lacks a 'length' property, which would be expected for an array.

How do I cast ChatMessage[] properly so that ChatMessageStackView calls render() without error? Why does messages become a nested object when I reference this.props.stack?

Here is the example:

import RX = require('reactxp');
import { VirtualListView, VirtualListViewItemInfo } from 'reactxp-virtuallistview';

export interface ChatMessage extends VirtualListViewItemInfo {
    content: string,
    username: string,
    timestamp: string 
}

interface ChatMessageStackProps {
    stack: ChatMessage[];
}

export const ChatMessageStack = (messages:ChatMessage[]) =>
    (
        <VirtualListView
            itemList={messages}
            renderItem={renderMessage}
            animateChanges={ true }
            skipRenderIfItemUnchanged={ true }
        />
    )

function renderMessage(message:ChatMessage, hasFocus?: boolean) {
    return (
        <RX.View>
            <RX.Text>
                {message.timestamp} {message.username} {message.content}
            </RX.Text>
        </RX.View>
    )
}

export class ChatMessageStackView extends RX.Component<ChatMessageStackProps, RX.Stateless> {
    constructor(props:ChatMessageStackProps) {
        super(props);
    }

    render() {
        return (
            <ChatMessageStack messages={this.props.stack}/>
        );
    }
}

Thanks for your help.

Upvotes: 0

Views: 164

Answers (2)

Frexuz
Frexuz

Reputation: 4933

Your type signature is incorrect in ChatMessageStack.

The argument is actually props, but you are trying to get messages.

If you look closer at the error message, it actually explains it well.
It's not trying to get length of messages, it's trying to do it on the object, like so { messages: ChatMessage[]; }.length. The object is props in this case.

Either use props.messages or change the type signature to:

export const ChatMessageStack = ({ messages } { messages: ChatMessage[] }) => 

Upvotes: 1

uyghurbeg
uyghurbeg

Reputation: 310

try to set this ChatMessage[] like: ChatMessage:any[]

Upvotes: 0

Related Questions