tobemaster56

ts 中,访问对象的属性,如何获得更准确的类型

  •  
  •   tobemaster56 · Jan 10, 2022 · 2428 views
    This topic created in 1591 days ago, the information mentioned may be changed or developed.
    interface MyProps {
      x: number;
      y: string;
    }
    
    const myVar: MyProps = {
      x: 1,
      y: '2',
    };
    
    function getMyValue(prop?: keyof MyProps) {
      if (prop) {
        return myVar[prop];
      }
      return myVar;
    }
    
    const x = getMyValue('x');
    const y = getMyValue('y');
    const val = getMyValue();
    

    这个时候,x 的类型 is 'string' | 'number' | MyProps, 但是我预期的类型 x is 'number'. y is 'string', and val is MyProps. 怎么做比较优雅

    5 replies    2022-01-12 11:21:49 +08:00
    shakaraka
        1
    shakaraka  
    PRO
       Jan 10, 2022
    就不应该有这个 getMyValue 方法。直接 myVar.x 不就是 number 了么?直接 value = object.key 。还是说你有什么特殊场景
    TarotVoyager
        2
    TarotVoyager  
       Jan 10, 2022   ❤️ 1
    function getMyValue<T extends keyof MyProps>(prop: T): MyProps[T];
    function getMyValue(): MyProps;
    function getMyValue<T extends keyof MyProps>(prop?: T) {
    if (prop) {
    return myVar[prop];
    }
    return myVar;
    }
    tobemaster56
        3
    tobemaster56  
    OP
       Jan 10, 2022
    @wunonglin 这里是被我简化了,我的场景是获取 React 的 context 的值, 参考 2 楼的回答,已经解决了

    ```
    import * as React from 'react';
    import { ConfigConsumerProps, ConfigContext } from '../ConfigContext';

    type ConfigConsumerKeys = keyof ConfigConsumerProps;

    type ConfigType = Exclude<
    ConfigConsumerKeys,
    'rootPrefixCls' | 'iconPrefixCls' | 'locale' | 'theme'
    >;

    export function useComponentConfig(): ConfigConsumerProps;
    export function useComponentConfig<T extends ConfigType>(
    type: T
    ): ConfigConsumerProps[T];

    export function useComponentConfig<T extends ConfigType = ConfigType>(
    configType?: T
    ): ConfigConsumerProps[T] | ConfigConsumerProps {
    const config = React.useContext(ConfigContext);
    if (configType) {
    return config[configType];
    }
    return config;
    }
    ```
    tobemaster56
        4
    tobemaster56  
    OP
       Jan 10, 2022
    @chouchoui 正常工作,谢谢
    fifa666
        5
    fifa666  
       Jan 12, 2022
    interface MyProps {
    x: number;
    y: string;
    }

    type getMyValue<P, T> = P extends keyof T ? T[P] : T

    type x = getMyValue<'x', MyProps>;
    type y = getMyValue<'y', MyProps>;
    type val = getMyValue<unknown, MyProps>;
    这样也可以
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1396 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 17:09 · PVG 01:09 · LAX 10:09 · JFK 13:09
    ♥ Do have faith in what you're doing.