How do I create a search form that searches only within a custom post type?

First, ensure that your custom post type is public and searchable

Second, you can’t use post_type url query var, it will be strip, its reserve for custom post type archive.

you can however simply do a custom post type search with URL like this.

domain.com/custom-post-type-rewrite-slug/?s=My+Search+Term

so in your form, the action should be

<?php echo esc_url(home_url('/custom-post-type-rewrite-slug/')); ?>

add remove this hidden input for post_type

<input type="hidden" name="post_type" value="myposts" />

Additionally, you can also set your own query var then modify the query via pre_get_posts action hook so you can perform search on tld with one or more post_type support.

Simply add query var first

add_filter( 'query_vars',  function( $vars ) {
    $vars[] = 'ptype';
    return $vars;
});

Now, modify the query if ptype is present in the URL

add_action('pre_get_posts', function( $query) {

    if ( !is_admin() && isset( $query->query['s'] ) && isset( $query->query['ptype'] ) ) {
        $query->set('post_type', $query->query['ptype']);
    }
    return $query;
    
}); 

Once added, you can do a search like bellow;

for searching on single post type

domain.com/?ptype=whatever&s=search+term

for searching on multiple post type

domain.com/?ptype[]=whatever&ptype[]=post&s=search+term

so if you want to support multiple post type on your search form, you can simply add multiple hidden input

<input type="hidden" name="ptype[]" value="whatever" />
<input type="hidden" name="ptype[]" value="post" />