How to get categories linked in posts for a specific post type

I found a custom solution, this is the function :

function get_all_categories_linked_to_post_type( $post_type ) {
    $a_terms = array();
    $the_query = get_posts_by_type($post_type);
    if( !empty( $the_query->posts ) ) {
        foreach ($the_query->posts as $post) {
            $terms = wp_get_post_terms($post->ID, 'category');
            if( !empty( $terms ) ){
                foreach ( $terms as $term ){
                    if (!array_key_exists( $term->term_id, $a_terms)) {
                        $a_terms[ $term->term_id ] = $term;
                    }
                }
            }
        }
    }
    return $a_terms;
}