Typescript with array data from shitty CMS

I'm trying to learn this typescript thing Theo's banging on about all the time but can't figure out how to do TS with arrays. I get an array from my CMS that fits with the ContentProps I made
type ContentProps = {
level: string;
name: string;
beskrivelse: string;
vurdering?: string;
}
type ContentProps = {
level: string;
name: string;
beskrivelse: string;
vurdering?: string;
}
This is the exact return I get from the CMS, but trying to typecheck this I get an error stating "allContent does not exist on type ContentProps[]" This is my attempt so far
type ContentProps = {
level: string;
name: string;
beskrivelse: string;
vurdering?: string;
}

const AuditConditionalRenderer = ({ allContent }: Array<ContentProps>) => {
type ContentProps = {
level: string;
name: string;
beskrivelse: string;
vurdering?: string;
}

const AuditConditionalRenderer = ({ allContent }: Array<ContentProps>) => {
PS: This works in the front end, but TS is not happy. Any ideas on what I'm doing wrong 🤔
6 Replies
word
word•2y ago
You're saying in your type that the props are an array of that object, but them you're trying to destructure a object property { allContent } from what should be an array. If your code works, you're receiving another thing and "lying" with ts
Vimes
VimesOP•2y ago
Sounds like something I would do. Code works and renders in front end. I did destructuring to save one level of "drilling" for props in child components. How should I use typescript with the desctured prop? 🤔 Or should I not do desctruturing here? Same error with
const AuditConditionalRenderer = ({ allContent }: ContentProps)
const AuditConditionalRenderer = ({ allContent }: ContentProps)
Would something like this be the "correct" way? Seems a bit reduntant
const AuditConditionalRenderer = ({ allContent }: {allContent: ContentProps}) => {
const AuditConditionalRenderer = ({ allContent }: {allContent: ContentProps}) => {
Brendonovich
Brendonovich•2y ago
yeah this is the correct way
word
word•2y ago
If ContentProps should be an array of those objects, them you could type it like that directly:
type ContentProps = {
level: string;
name: string;
beskrivelse: string;
vurdering?: string;
}[]
type ContentProps = {
level: string;
name: string;
beskrivelse: string;
vurdering?: string;
}[]
Brendonovich
Brendonovich•2y ago
if it were me i'd put the type in its own Props interface but that works too
Vimes
VimesOP•2y ago
Thanks! This solved my issue and made me ...a bit better at TS 🙂
Want results from more Discord servers?
Add your server