简体   繁体   English

不要在 generics 中重复 keyof 类型表达式

[英]Don't repeat keyof Type expression in generics

I don't want to repeat keyof T expression in here:我不想在这里重复keyof T表达式:

// This type is meant to achieve something like ReturnType<typeof Object.entries>
type ObjectEntries<T extends object> = [keyof T, T[keyof T]][];

So I do this but it doesn't work:所以我这样做但它不起作用:

type ObjectEntries<T extends object, U = keyof T> = [U, T[U]][];
// Type 'U' cannot be used to index type 'T'

However if U extends to keyof T , it works but why?但是,如果U扩展到keyof T ,它会起作用,但为什么呢?

type ObjectEntries<T extends object, U extends keyof T = keyof T> = [U, T[U]][];

U extends X means that U needs to be a type that extends X , it is also called a type constraint. U extends X意味着U需要是扩展X的类型,也称为类型约束。 If you leave it like this, U must be specified and you will get a compiler error if you don't specify it when instantiating ObjectEntries .如果你这样保留它,则必须指定U ,如果在实例化ObjectEntries时不指定它,你将收到编译器错误。

U = X means that if U is unspecified when instantiating ObjectEntries it will by default be X , but since U does not have any constraint, U could be any type whatsoever (for example string ). U = X意味着如果在实例化ObjectEntries时未指定U ,则默认情况下将为X ,但由于U没有任何约束,因此U可以是任何类型(例如string )。

Constraints and defaults serve different purposes and so if you want U to default to keyof T so you don't have to specify it you need the = keyof T , and if you also want to constrain U so only types that are subtypes of keyof T can be specified, you will need the extends keyof T .约束和默认值有不同的用途,因此如果您希望U默认为keyof T ,那么您不必指定它,您需要= keyof T ,如果您还想约束U ,那么只有keyof T的子类型类型可以指定,您将需要extends keyof T The constraint is what gives TyepScript enough information to know that it is safe to index T with U , since any specified type for U must be a subtype of keyof T该约束为 TyepScript 提供了足够的信息来知道用U索引T是安全的,因为U的任何指定类型都必须是keyof T的子类型

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

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