简体   繁体   English

我可以用另一种类型扩展一种类型吗?

[英]Can I extend a type with another type?

Consider the following type:考虑以下类型:

export type Collections = {
  users: User
  business: Business
  permissions: Permissions
  cards: Card
}

// note the Collections[keyof Collections] are just some custom types
// that are objects, but are irrelevant for the question

and let's say I want to create a type that extends the aforementioned type in Record<keyof Collections, unknown>假设我想在Record<keyof Collections, unknown>中创建一个扩展上述类型的类型

I know recently introduced the statisfies operator, but that is only useful for const not extending the types themelves.我知道最近介绍了statisfies运算符,但这只对const有用,不能扩展类型主题。

I know the shape of my desired type, ie我知道我想要的类型的形状,即

export type SubCollections = {
  cards: [CardLog, CardActions]
  users: [UserLog]
}

this works, however it's not very practical, because when I want to use a function这可行,但不是很实用,因为当我想使用 function

const subcollection = <K extends keyof Collections, S extends SubCollections[K]>(
  collection: K,
  sub: S
) => // ...

This throws a TypeError:这会引发 TypeError:

Type K cannot be used index type SubCollections类型K不能使用索引类型SubCollections

Which obviously I understand why it happens.这显然我明白为什么会这样。 I know I could create an artificial type-narrower ie我知道我可以创造一个人工类型更窄的即

type SharedKey<K extends keyof Collection> = K extends keyof SubCollections
 ? K
 : never

export const subcollection = <
  K extends keyof Collections,
  S extends SharedKey<K>
>(collection: K, subcol: S) => // ...
// ^ this works!

But this still feels rather clumsy if I had to individually narrow the argument in every single use-case.但是,如果我必须在每个单独的用例中单独缩小论点,这仍然感觉相当笨拙。

Is there perhaps a way I could tell typescript, that the two types share the same keys?有没有办法告诉 typescript,这两种类型共享相同的密钥?

// something akin to (obviously this is invalid syntax)
export type SubCollections extends Record<keyof Collections, unknown[]> = {
  cards: [CardLog, CardActions]
  users: [UserLog]
}

Is this might helps?这可能有帮助吗?

type Commonkeys<A, B> = keyof A extends infer keyofA ? (keyofA extends keyof B ? keyofA : never) : never;

type AAA = Commonkeys<Collections, SubCollections>;
//  type AAA = "cards" | "users"

const subcollection = <K extends Commonkeys<Collections, SubCollections>, S extends SubCollections[K]>(collection: K, sub: S) => {};

Update thanks to vera:感谢 vera 的更新:

    const subcollection = <K extends keyof Collections & keyof SubCollections, S extends SubCollections[K]>(
  collection: K,
  sub: S
) => {};

Seems so simple now...现在看起来很简单...

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

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