cari

Rumah  >  Soal Jawab  >  teks badan

Bolehkah jenis dalam TypeScript disimpulkan daripada PropTypes?

<p>Saya tahu cara membuat kesimpulan jenis dalam kes ini: </p> <pre class="brush:php;toolbar:false;">import PropTypes daripada 'prop-types'; alat peraga = { id: PropTypes.number, }; jenis Props = PropTypes.InferProps<jenis props>; const x: Props = {}; x.id; // nombor |. <p>Walau bagaimanapun, dalam kes saya, saya mempunyai:</p> <pre class="brush:php;toolbar:false;">const propsShape = PropTypes.shape({ id: PropTypes.number, // Lebih banyak sifat termasuk panggilan PropTypes.shape bersarang });</pre> <p>Jika saya mencuba: </p> <pre class="brush:php;toolbar:false;">type PropsFromShape = PropTypes.InferProps<typeof propsShape>; const y: PropsFromShape = {}; const z = y.id;</pre> <p>Ia gagal untuk disusun: </p> <pre class="brush:php;toolbar:false;">Taip '{}' tidak boleh diperuntukkan untuk menaip 'PropsFromShape'. Harta 'isRequired' tiada dalam jenis '{}' tetapi diperlukan dalam jenis 'InferPropsInner<Pick<Requireable<InferProps<{ id: Requireable<number>;, "isRequired">>'. 'id' harta tidak wujud pada jenis 'PropsFromShape'.</pre> <p>Saya boleh mengekstrak parameter <code>shape</code> ke dalam pemalar yang berasingan dan lakukannya seperti di atas, tetapi adakah terdapat cara untuk membuat kesimpulan terus jenis sifat daripada <code>propsShape</code> Cara yang baik? </p>
P粉715304239P粉715304239553 hari yang lalu546

membalas semua(1)saya akan balas

  • P粉872101673

    P粉8721016732023-08-15 09:53:53

    Untuk dapatkan jenis objek bersarang boleh gunakan type NestedProps = PropTypes.InferProps<typeof propsShape>['isRequired'];

    import PropTypes from "prop-types";
    
    const propsShape = PropTypes.shape({
      nestedId: PropTypes.number,
      // 更多包括嵌套的PropTypes.shape调用的属性
    });
    
    const props = {
      id: PropTypes.number,
      optionalWithShape: propsShape
    };
    
    type Props = PropTypes.InferProps<typeof props>;
    type NestedProps = PropTypes.InferProps<typeof propsShape>['isRequired'];
    
    const x: Props = {};
    x.id = 1;
    
    const y: NestedProps = {
      nestedId: 1
    }
    
    x.optionalWithShape = y;

    Atau jika anda boleh meletakkan keseluruhan definisi prop di satu tempat:

    import PropTypes from "prop-types";
    
    const props = {
      id: PropTypes.number,
      optionalWithShape: PropTypes.shape({
        nestedId: PropTypes.number
      })
    };
    
    type Props = PropTypes.InferProps<typeof props>;
    type NestedProps = Props['optionalWithShape'];
    
    const x: Props = {};
    x.id = 1;
    
    const y: NestedProps = {
      nestedId: 1
    }
    
    x.optionalWithShape = y;
    
    console.log(x.optionalWithShape.nestedId);

    Saya secara peribadi berpendapat yang kedua lebih mudah dibaca.

    balas
    0
  • Batalbalas