1

I have this Svelte 5 code:

<script lang="ts">
    type BaseProps = {
        required?: boolean;
    };

    type SingleDateProps = BaseProps & {
        range?: false | undefined;
        dates?: Date | null;
        onchange?: (e: Date | undefined) => void;
    };

    type RangeDateProps = BaseProps & {
        range: true;
        dates?: Date[] | null;
        onchange?: (e: Date[] | undefined) => void;
    };

    type Props = SingleDateProps | RangeDateProps;

    let {
        dates = $bindable(),
        range = false,
        onchange
    }: Props = $props();
</script>

in this component the dates are properly seen like dates: Date[] | undefined (note the range prop):

<DateComponent
    range
    onchange={(dates) => {
        // use dates here
    }}
/>

if I use this component instead (without the range prop):

<DateComponent
    onchange={(dates) => {
        // use dates here
    }}
/>

dates now is seeing like any:

Parameter 'dates' implicitly has an 'any' type. ts(7006)

(parameter) dates: any

Why?

0

2 Answers 2

1

Looks like a bug, bare TS works.

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

Comments

0

Use generics. The following works:

<script lang="ts" generics="T extends boolean = false">
    import Self from './Test.svelte';

    type Props = {
        range?: T;
        dates?: T extends false ? Date : [Date, Date];
        onChange?: (dates: T extends true ? [Date, Date] : Date) => void;
    };

    let {
        range,
        dates,
        onChange
    }: Props = $props();
</script>

<Self range dates={[new Date(), new Date()]} onChange={(dates) => {}} />
<Self dates={new Date()} onChange={(date) => {}} />

How It Works

Using generics in components usually require a default type because, at least at present time, the Svelte language tools cannot infer the type of T when the property that defines T is not specified, which is the case for the range property.

Anyway, copy the code snippet into a Test.svelte file in your IDE and verify the types of properties and the parameter types in the onChange callback. They should all be OK.

Comments

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.