简体   繁体   English

FlowType : 函数的返回类型 (k) => obj[k]

[英]FlowType : return type of function (k) => obj[k]

I have a User object:我有一个User对象:

type User = {
  name: string,
};

That has a get() function, that takes in parameter the key of an attribute on User and returns this attribute.它有一个get()函数,它在参数中接受User属性的键并返回该属性。 The function get is函数get是

User.prototype.get = (prop) => {
  return this[prop];
};

How can I write this fonction definition ?我该如何编写这个函数定义? Here's what I got so far:这是我到目前为止所得到的:

type User = {
  name: string,
  get: (k: $Keys<User>) => any, // How can I change any to the correct property type ?
};

Seems like you can use now $ElementType<T, K> .似乎您现在可以使用$ElementType<T, K> To be confirmed !待确认!

Source: https://github.com/facebook/flow/issues/4122#issuecomment-314700605来源: https : //github.com/facebook/flow/issues/4122#issuecomment-314700605


EDIT: Working example编辑: 工作示例

/* @flow */

type User = {
  name: string,
  age: number,
}

const user: User = {
  name: 'Ilyes',
  age: 21,
}

function get<K: string>(key: K): $ElementType<User, K> {
  return user[key];
}

const number: number = get('name'); // error
const number2: number = get('age'); // works
const string: string = get('name'); // works
const string2: string = get('age'); // error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM