#Is it possible to add a default value to the level property?

16 messages · Page 1 of 1 (latest)

young sparrow
#

hello, I wonder if there is a way to set a default value to the level property:

export interface NavItemProps<T> {
    id: string;
    title: string;
    path: string;
    metaData?: NavMetaData;
    subNav?: NavItemProps<T>[];
}

export interface NavMetaData {
    level: string;
    fileType: string;
}

// how I am using the Interface
const SideNavMenu = ({items}:{ items: NavItemProps<string>[]}) => {
    // ....
};
vivid current
#

no, it's not possible
at least not when using types or interfaces

#

types or interfaces don't exist at runtime, so they can't hold values

#

they are only used at compile-time to ensure your code is correct and you are not trying to access a property that does not exist

#

if you want to provide a default value, you could try merging your object with another object holding default values

#

also, a few things

#

instead of writing { items }: { items: NavItemProps<string>[] }, you could write items: NavItemProps<string>[]

obtuse wolfBOT
#
ascor8522#0

Preview:```ts
export interface NavItemProps<T> {
id: string;
title: string;
path: string;
metaData?: NavMetaData;
subNav?: NavItemProps<T>[];
}

export interface NavMetaData {
level: string;
fileType: string;
}

// how I am using the Interface
...```

vivid current
#

!ts

obtuse wolfBOT
#
export interface NavItemProps<T> {
    id: string;
    title: string;
    path: string;
    metaData?: NavMetaData;
    subNav?: NavItemProps<T>[];
}

export interface NavMetaData {
    level: string;
    fileType: string;
}

// how I am using the Interface
const SideNavMenu = (items: NavItemProps<string>[]) => {
    items = items
        .map(item => ({
            ...item,
            metaData: {
                level: item.metaData?.level ?? "default level value",
                fileType: item.metaData?.level ?? "default fileType value",
            },
        }));
};
vivid current
#

this way you can provide a default value for each item's level and fileType

#

tho it's a big verbose

#

it's usually better to give a default value right after creating the object or when trying to access the property

#

@young sparrow

young sparrow
#

@vivid current awesome sir! thanks a lot for this great explanation!

long vault
#

!close