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. 怎么做比较优雅
1
wunonglin 2022-01-10 18:32:11 +08:00
就不应该有这个 getMyValue 方法。直接 myVar.x 不就是 number 了么?直接 value = object.key 。还是说你有什么特殊场景
|
2
chouchoui 2022-01-10 18:38:24 +08:00 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; } |
3
tobemaster OP @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; } ``` |
4
tobemaster OP @chouchoui 正常工作,谢谢
|
5
fifa666 2022-01-12 11:21:49 +08:00
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>; 这样也可以 |