2

这是我天真的尝试将泛型类型从参数对象类型MyObject<P>转换为回调函数。

interface PropsType {
  value: number;
}

class MyObject<P extends PropsType> {
  readonly props: P;

  constructor(props: P) {
    this.props = props;
  }
}

function doSomething<P extends PropsType, T extends MyObject<P>>(
  object: T,
  callback: (props: P) => number
): number {
  return callback(object.props);
}

const myProps = {
  value: 21,
  otherValue: 42
}
const myObject = new MyObject(myProps);

// In the callback, props is of type PropsType
doSomething(myObject, (props) => props.otherValue);
// [ts] Property 'otherValue' does not exist on type 'PropsType'.

myObject正如预期的那样,的类型是MyObject<{ value: number, otherValue: number }>,所以我期望泛型类型会传播到doSomethingP将是{ value: number, otherValue: number },然后props也将是那种类型。

但是,错误清楚地表明props是 类型PropTypes,这是 P 可能的最小类型。

有没有办法告诉 Typescript 编译器将完整的P定义传递给回调,而不是像这样显式地强制类型?

doSomething<
  (typeof myObject)['props'],
  typeof myObject
>(myObject, (props) => props.otherValue);
4

1 回答 1

0

让打字稿根据另一个类型参数推断一个类型参数通常不起作用。在这种情况下,您可以使用类型查询:

function doSomething<T extends MyObject<PropsType>>(
    object: T,
    callback: (props: T['props']) => number
 ): number {
    return callback(object.props);
}

doSomething(myObject, (props) => props.otherValue); //works
于 2018-05-10T10:49:21.200 回答