1

I'm trying to create a component that can receive a prop that is an object.

If the object is not set, I want to define a default value for it.

<script setup lang="ts">
interface LocaleText {
  text: string;
  single?: boolean;
  count?: number;
  params?: any;
}
interface Title {
  title?: LocaleText;
}
interface Filter extends Title {
  items?: string[];
}
interface Props extends Title {
  filters?: Filter[];
}
interface Data {
  selectedStatus: string;
}
const props = withDefaults(defineProps<Props>(), {
  title: (): LocaleText => ({ text: "ExampleText" }),
  filters: () => [] as Filter[],
});

function getText(text?: LocaleText): string | undefined | null {
  return text?.text ?? "null";
}
</script>
<template>
  <div>
    Example:
    {{ getText(props.title) }}
  </div>
</template>

Page is currently displaying "Example:null"

I could not figure out why this is happening.

4
  • What about {{ getText(title) }}? Commented Oct 6, 2022 at 5:30
  • I've just tested with yor suggestion but didn't work. As far i know i need to use use props.title Commented Oct 6, 2022 at 5:33
  • What do you expect? Commented Oct 6, 2022 at 5:46
  • If no :title prop is passed, i want to set a default value to it. Commented Oct 6, 2022 at 5:48

1 Answer 1

4

According to this in official docs :

As of now, the type declaration argument must be one of the following to ensure correct static analysis:

  • A type literal
  • A reference to an interface or a type literal in the same file

So the props should be a simple interface without extending another one :

<script setup lang="ts">
interface LocaleText {
  text: string;
  single?: boolean;
  count?: number;
  params?: any;
}
interface Title {
  title?: LocaleText;
}
interface Filter extends Title {
  items?: string[];
}
interface Props  {
  title:string;
  single?: boolean;
  count?: number;
  params?: any;
  filters?: Filter[];
}
interface Data {
  selectedStatus: string;
}
const props = withDefaults(defineProps<Props>(), {
  title: LocaleText => ({ text: "ExampleText" }),
  filters: () => [] as Filter[],
});

function getText(text?: LocaleText): string | undefined | null {
  return text?.text ?? "nullVal";
}
</script>
<template>
  <div>
    Example:
   {{ getText(props.title) }}
  </div>
</template>

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, i din't know that i couldn't extends another interface

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.