这是我发现的最好的方法:
namespace Unique {
export declare const Newtype: unique symbol
export declare const JPY: unique symbol
export declare const GBP: unique symbol
}
type Newtype<A, B extends symbol> = A & { readonly [Unique.Newtype]: B }
type JPY = Newtype<number, typeof Unique.JPY>
type GBP = Newtype<number, typeof Unique.GBP>
const test: <A extends symbol>(a: Newtype<number, A>, b: Newtype<number, A>) => Newtype<number, A>
= (a, b) => a + b as any // massage the type checker a bit
// fails
test(10 as GBP, 10)
test(10 as GBP, 10 as JPY)
// passes
test(10 as GBP, 10 as GBP)
test(10 as JPY, 10 as JPY)
成立,但这里没有奖励积分,因为您最终会收到一些包含文件路径的非常讨厌的错误消息(现场示例,请参阅“错误”)Newtype<number, typeof import("file:///input").JPY>
:。我希望有一种涉及接口扩展或类似的方法来使这个更干净。
成立,因为两者Unique.Newtype
都是Unique.JPY
s unique symbol
。
成立,因为我们可以使用结构Newtype
来确保类型是肯定的Newtype
,因为它是根据Unique.Newtype
which is定义的unique symbol
。