我有一个 TypeScript 函数,它解析一些 JSON 并通过类型保护运行它以确保数据有效,以便编译时代码的其余部分知道它正在处理一个实际遵守预期接口的对象。
但是,我很难让 TypeScript 强制执行类型保护。显然JSON.parse
返回any
,它可以分配给任何其他类型,因此会检查,即使我指定了非any
返回类型。
const validPerson = `{"firstName": "John", "lastName": "Doe"}`;
const invalidPerson = `{"foo": 123}`;
interface Person {
firstName: string;
lastName: string;
}
interface PersonGetter {
(json: string): Person | undefined;
}
function isPerson(o: any): o is Person {
return typeof o.firstName === "string" && typeof o.lastName === "string";
}
// BAD: Type checks, but it's overly permissive. `JSON.parse` could return anything.
const getPerson1: PersonGetter = (json) => {
const o = JSON.parse(json);
return o;
}
// GOOD (kinda): Requires type guard to pass.
// `unknown` requires TS 3, which is fine in general, but bad for me.
// Also, I feel like having to remember to case the return from `JSON.parse` is a responsibility the programmer shouldn't bear.
const getPerson2: PersonGetter = (json) => {
const o: unknown = JSON.parse(json);
if (isPerson(o)) {
return o;
} else {
return undefined;
}
}
// GOOD (kinda): Requires type guard to pass. Works in TS 2.8.
// Still, not great that I have to cast the return value from `JSON.parse`, but I could probably work around that.
type JSONPrimitive = string | number | boolean | null;
type JSONValue = JSONPrimitive | JSONObject | JSONArray;
type JSONObject = { [member: string]: JSONValue };
interface JSONArray extends Array<JSONValue> {}
const getPerson3: PersonGetter = (json) => {
const o: JSONValue = JSON.parse(json);
if (isPerson(o)) {
return o;
} else {
return undefined;
}
}
选项 3 对我有用,但它使用的建议 JSON 类型仍有争议,并且仍然将责任放在实现者身上(他们可以很容易地根本不使用类型保护,并且仍然认为他们遵守接口)。
看来JSON.parse
返回any
是我的问题的根源。我已经在strict
模式下运行,但它似乎仍然允许将显式键入的内容any
扩展为函数的显式返回类型。
有没有另一种方法告诉 TypeScript 函数的返回值必须是它实现的接口中指定的返回类型,而不是any
?