typescript 如何在不禁用类型检查的情况下将对象强制转换为类型?

u0njafvf  于 2023-08-08  发布在  TypeScript
关注(0)|答案(1)|浏览(89)

as<>都完全忽略类型检查。我可以使用类似下面的函数来做同样的事情,同时检查类型,但我想知道是否有一个内置的机制来做同样的事情,以减少无用的公共函数的数量(因为它是大多数语言中的常见结构)?

const cast = <T>(x: T) => x

字符串
为了解释为什么需要这样做-我将一个对象字面量传递给泛型函数,我需要确保它被视为某种类型,同时还要确保我没有忘记任何属性。

6yt4nkrj

6yt4nkrj1#

若要将变量强制转换为更宽的类型,请为其创建一个新变量:

interface Foo {
  a: number;
  b: string;
}
interface Bar {
  a: number;
}

const foo: Foo = { a: 1, b: '2' }
const notFoo = { a: 'string' }

// casting foo to `Bar` type, with assignability check
const bar: Bar = foo;

const notBar: Bar = notFoo;
//    ~~~~~~
// Type '{ a: string; }' is not assignable to type 'Bar'.
//   Types of property 'a' are incompatible.
//     Type 'string' is not assignable to type 'number'.(2322)

字符串

相关问题