【问题标题】:Typescript using & operator on string type在字符串类型上使用 & 运算符的打字稿
【发布时间】:2022-07-21 20:03:46
【问题描述】:

我在 TS 文档中找到了此代码。 https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html#string-unions-in-types

“字符串&”是什么意思?我以为它只能用在接口上。

type PropEventSource<Type> = {
    on(eventName: `${string & keyof Type}Changed`, callback: (newValue: any) => void): void;
};

【问题讨论】:

  • I thought it could only be used on interfaces. 事实上,你可以写成string &amp; number。它计算为never,但它确实编译了。

标签: typescript


【解决方案1】:

&amp; 用于制作交集类型。如果您熟悉使用数学集,那么您也可以利用这些知识来了解它如何处理类型,因为两种类型之间的交集与 intersection between two sets 非常相似。

string 类型是所有可能字符串的集合。所以"a""aa""aaa"等。keyof TypeType中所有键的集合。例如,假设 Type 有 3 个键:"name""id"0(最后一个是数字,而不是字符串)。当您将这些类型相交时,结果是两个集合的交集:string &amp; keyof Type 只是两个集合中都显示的值。所以"name""id" 在交叉路口找到,但"aaa" 不是(它只在string)和0 不是(它只在keyof Type)。

简而言之:string &amp; keyof Typekeyof Type 相同,但不包括所有数字。

【讨论】:

    猜你喜欢
    • 2022-10-14
    • 1970-01-01
    • 2020-03-01
    • 2021-08-25
    • 1970-01-01
    • 2016-02-25
    • 2020-07-26
    • 2018-04-28
    • 2022-01-03
    相关资源
    最近更新 更多