断言类型A可赋值给类型b



假设我有从第三方库导入的类型T1。假设类型T1定义为:

type T1 = {
a: number | string
b: 'b1' | 'b2' | 'b3'
c?: boolean
}

现在我想定义类型T2如下:

type T2 = {
a: number
b: 'b1' | 'b2'
}

只要需要T1类型的对象,就可以使用T2类型的对象。

我怎么能显式地断言,在T2被定义的地方,如果不是这样,Typescript的类型检查器会报错?

我期待如下内容:

assert_assignable_to<T1, T2>()

我假设我可以使用Omit,Pick&的组合从T1构造类型T2,但我想在我的代码中明确断言T2的实例可以分配给T1

任何想法?

可以使用泛型。操场上

// Defined in external library
type Subtype = {
a: number | string
b: 'b1' | 'b2' | 'b3'
c?: boolean
}
// Want to define internally while checking if it's a supertype
// type Supertype = {
//     a: number
//     b: 'b1' | 'b2'
// }
// Behold!
export type CreateSupertypeOf<Sub extends Super, Super> = Super;
// Fails if not a supertype
type Supertype = CreateSupertypeOf<Subtype, {
a: number
b: 'b1' | 'b2'
}>

注意,在这个例子中,Suptype不能分配给Supertype。看来你对变异的理解混淆了(在这里阅读更多关于变异和亚型的内容)。

Type 'Subtype' does not satisfy the constraint '{ a: number; b: "b1" | "b2"; }'.
Types of property 'a' are incompatible.
Type 'string | number' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.

你可能指的是这个(游乐场):

type Subtype = {
a: number
b: 'b1' | 'b2'
c?: boolean
}
type Supertype = CreateSupertypeOf<Subtype, {
a: number | string
b: 'b1' | 'b2' | 'b3'
}>

您可以定义T2来扩展T1

interface T2 extends T1 {
a: number
b: 'b1' | 'b2'
}

如果T2不能赋值给T1,你会得到一个错误

游乐场

最新更新