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

2022-01-10 18:21:19 +08:00
 tobemaster
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. 怎么做比较优雅

1382 次点击
所在节点    TypeScript
5 条回复
wunonglin
2022-01-10 18:32:11 +08:00
就不应该有这个 getMyValue 方法。直接 myVar.x 不就是 number 了么?直接 value = object.key 。还是说你有什么特殊场景
chouchoui
2022-01-10 18:38:24 +08:00
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;
}
tobemaster
2022-01-10 18:43:22 +08:00
@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;
}
```
tobemaster
2022-01-10 18:43:43 +08:00
@chouchoui 正常工作,谢谢
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>;
这样也可以

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/827394

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX