我有一个从服务器发送到浏览器的JSON对象。从那个 JSON 对象中,我想检查它是否是某个类的实例(换句话说,检查它们的类属性是否存在于 JSON 对象中(,而不会进行任何会减慢我的代码速度的循环。
我有课程:
export class MyClass implements IInterface {
type: MyType = "Page";
isAbsolute: boolean = false;
}
界面:
export interface IInterface {
type: MyType
}
我的类型:
export type MyType = "Page" | "Other"
在JavaScript中,我曾经检查它是否是这样的页面:
if("type" in theObject && theObject.type === "Page"){
//so it's a page
}
如果我必须在打字稿中这样做,我没有理由使用 Typescript 而不是 Javascript。
我通过创建一个对象进行了一些测试,但typeof
和instanceof
不知道它们是否兼容。
let page1 = {'type': "Page", "isAbsolute": true};
let page1Cast = page1 as MyClass;
let anyCast = {"hello": "world"} as MyClass;
let page2 = new MyClass();
page2.isAbsolute = true;
console.log("typeof", typeof page1);
console.log("page1", page1);
console.log("page2", page2);
console.log("page1 instanceof", page1 instanceof MyClass);
console.log("page2 instanceof", page2 instanceof MyClass);
console.log("page1Cast instanceof", page1Cast instanceof MyClass);
console.log("anyCast instanceof", anyCast instanceof MyClass);
输出为:
typeof object
page1 {type: "Page", isAbsolute: true}
page2 MyClass {type: "Page", isAbsolute: true}
page1 instanceof false
page2 instanceof true
page1Cast instanceof false
anyCast instanceof false
如何检查page1
是否是 wihotut 类型MyClass
就像我以前在 JS 中那样做(检查每个属性是否存在,并且值是否存在或循环(?
如果您知道从服务器获取的 JSON 对象的类型,则可以强制转换它。例如:
interface MyJSONObject {
someProperty: number
}
fetch(...)
.then((result) => result.json())
.then((myObject: MyJSONObject ) => {
console.log(myObject.someProperty)
})
请注意,无需检查属性。
但是,如果你不知道对象的类型,那么你怎么能指望TypeScript知道它呢?在这种情况下,某种属性检查是唯一的方法。但是,类型联合使它变得漂亮。
interface JSONObjectWithNumber {
myNumber: number
}
interface JSONObjectWithString {
myString: string
}
JSONObjectOnServer = JSONObjectWithNumber | JSONObjectWithString
fetch(...)
.then((result) => result.json())
.then((myObject: JSONObjectOnServer) => {
// Conclude type of object, by checking for a conclusive property.
if ('myNumber' in myObject) {
// TypeScript automatically concludes, that the object must be JSONObjectWithNumber.
console.log(myObject.myNumber)
} else {
// TypeScript automatically concludes, that the object must be JSONObjectWithString.
console.log(myObject.myString)
}
})