Typescript - 如何使用通用定义中的完整类型?

Typescript - How to use full types from a generic definition?

这是我天真的尝试,将 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);

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

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

doSomething(myObject, (props) => props.otherValue); //works