简体   繁体   English

Typescript 条件类型未确定类型

[英]Typescript Conditional Types Not Figuring Out Type

Playground link 游乐场链接

Assuming the given type:假设给定类型:

export declare type MongoManagerFilter<T> = {
  [P in keyof T]?: (P extends keyof T ? T[P] : any);
};

When trying to specify the filter:尝试指定过滤器时:

update.$setOnInsert.createdAt = new Date();

I get this error:我收到此错误:

Type 'Date' is not assignable to type '"createdAt" extends keyof T ? T[keyof T & "createdAt"] : any'.ts(2322)

But if I change the filter to this it works:但是,如果我将过滤器更改为此它可以工作:

export declare type MongoManagerFilter<T> = {
  [P in keyof T]?: any;
};

Why does the conditional statement not actually figure out the type?为什么条件语句实际上并没有弄清楚类型? It's just keeping the code as the type.它只是将代码保留为类型。

I know the filter doesn't make sense how it is, I have another type instead of keyof T to catch dot notation, but I am having the same issue with conditional statements not figuring out the actual type.我知道过滤器没有意义,我有另一种类型而不是keyof T来捕获点表示法,但是我遇到了同样的问题,条件语句无法确定实际类型。

Full example完整示例

interface CollectionDocument {
  _id?: string;
  createdAt: Date;
}

type PathImpl<T, Key extends keyof T> =
  Key extends string
  ? T[Key] extends Record<string, any>
    ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof Date | keyof Object | keyof string> & string>}`
      | `${Key}.${Exclude<keyof T[Key], keyof Date | keyof Object | keyof string> & string}`
    : never
  : never;

type Path<T> = keyof T | PathImpl<T, keyof T>;

type PathValue<T, P extends Path<T>> =
    P extends `${infer Key}.${infer Rest}`
    ? Key extends keyof T
      ? Rest extends Path<T[Key]>
        ? PathValue<T[Key], Rest>
        : never
      : never
    : P extends keyof T
      ? T[P]
      : any;

export declare type MongoManagerFilter<T> = {
    [P in Path<T>]?: PathValue<T, P>;
};

export class MongoManagerCollection<T extends CollectionDocument> {
  constructor() {}
  
  updateOne(filter: MongoManagerFilter<T>) {
    // THIS DOES NOT WORK
    filter._id = '';
    filter.createdAt = new Date();
  }
}

// THIS WORKS
let testModel = new MongoManagerCollection<CollectionDocument>();
testModel.updateOne({_id: 'test', createdAt: new Date()});

Generic type T in:通用类型T在:

export class MongoManagerCollection<T extends CollectionDocument> {
  constructor() { }

  updateOne(filter: MongoManagerFilter<T>) {
    // THIS DOES NOT WORK
    filter._id = '';
    filter.createdAt = new Date();
  }
}

is a black box.是一个黑匣子。 filter._id is resolved as a non evaluated conditional type. filter._id被解析为非评估条件类型。 Treat it as a non called function.将其视为非称为 function。 Function which is has never been called does not return any value.从未调用过的 Function 不返回任何值。 Same is with filter._id . filter._id也是如此。 filter._id coresponds to this: filter._id对应于此:

type PathValue<T, P extends Path<T>> =
  P extends `${infer Key}.${infer Rest}`
  ? Key extends keyof T
  ? Rest extends Path<T[Key]>
  ? PathValue<T[Key], Rest>
  : never
  : never
  : P extends keyof T ////////////////////////////////////////////////
  ? T[P]              // Property is resolved as a conditional type //
  : any;              ///////////////////////////////////////////////

As you might have noticed, filter._id is P extends keyof T? T[P]: any您可能已经注意到, filter._idP extends keyof T? T[P]: any P extends keyof T? T[P]: any instead of just T[P] . P extends keyof T? T[P]: any而不仅仅是T[P]

There is a workaround.有一种解决方法。 You can use T[P & keyof T] instead of conditional type .您可以使用T[P & keyof T]代替conditional type See working example:请参阅工作示例:

interface CollectionDocument {
  _id?: string;
  createdAt: Date;
}

type PathImpl<T, Key extends keyof T> =
  Key extends string
  ? T[Key] extends Record<string, any>
  ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof Date | keyof Object | keyof string> & string>}`
  | `${Key}.${Exclude<keyof T[Key], keyof Date | keyof Object | keyof string> & string}`
  : never
  : never;

type Path<T> = keyof T | PathImpl<T, keyof T>;

type PathValue<T, P extends Path<T>> =
  P extends `${infer Key}.${infer Rest}`
  ? Key extends keyof T
  ? Rest extends Path<T[Key]>
  ? PathValue<T[Key], Rest>
  : never
  : never
  : T[P & keyof T]

export declare type MongoManagerFilter<T> = {
  [P in Path<T>]?: PathValue<T, P>;
};

export class MongoManagerCollection<T extends CollectionDocument> {
  constructor() { }

  updateOne(filter: MongoManagerFilter<T>) {
    filter._id = ''; // ok
    filter.createdAt = new Date(); // ok
    filter.createdAt = 'sdf'; // expected error

  }
}

// THIS WORKS
let testModel = new MongoManagerCollection<CollectionDocument>();
testModel.updateOne({ _id: 'test', createdAt: new Date() });

Playground操场

If you are interested in path implementation, you can take a look at this answer, this utility and/or my article .如果您对path实现感兴趣,可以查看答案、 此实用程序和/或我的文章

I don't know MongoDB api and the requirements of your types so I can't say whether they need to be modified or not.我不知道 MongoDB api 和你的类型的要求,所以我不能说它们是否需要修改。

Also, you can get rid of generic:此外,您可以摆脱泛型:

export class MongoManagerCollection {
  constructor() { }

  updateOne(filter: MongoManagerFilter<CollectionDocument>) {
    filter._id = ''; // ok
    filter.createdAt = new Date(); // ok

  }
}

// THIS WORKS
let testModel = new MongoManagerCollection();
testModel.updateOne({ _id: 'test', createdAt: new Date() });

but I don't think this is what you want.但我不认为这是你想要的。

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

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