[英]Typescript property type guards on unknown
我正在嘗試輸入保護未知類型
const foo = (obj: unknown) => {
if (typeof obj === 'object' && obj) {
if ('foo' in obj && typeof obj.foo === 'string') {
return obj.foo;
}
}
};
“對象”類型上不存在屬性“foo”。
我也試過 is 表達式不起作用:
const foo = (obj: unknown): obj is { foo: 'string' } => {
if (typeof obj === 'object' && obj) {
if ('foo' in obj && typeof obj.foo === 'string') {
return obj;
}
}
throw new Error();
};
請考慮使用這個助手:
const hasProperty = <Obj, Prop extends string>(obj: Obj, prop: Prop)
: obj is Obj & Record<Prop, unknown> =>
Object.prototype.hasOwnProperty.call(obj, prop);
在你的情況下。 in
操作符主要與工會一起按預期工作。 請看這里,這里和這里
工作解決方案:
const hasProperty = <Obj, Prop extends string>(obj: Obj, prop: Prop)
: obj is Obj & Record<Prop, unknown> =>
Object.prototype.hasOwnProperty.call(obj, prop);
const foo = (obj: unknown) => {
if (typeof obj === 'object' && obj) {
if (hasProperty(obj, 'foo') && typeof obj.foo === 'string') {
return obj.foo;
}
}
};
但是,由於您想在obj
無效時拋出錯誤,因此可以使用assert function
:
const hasProperty = <Obj, Prop extends string>(obj: Obj, prop: Prop)
: obj is Obj & Record<Prop, unknown> =>
Object.prototype.hasOwnProperty.call(obj, prop);
function foo(obj: unknown): asserts obj is { foo: string } {
const isValid =
typeof obj === 'object' &&
obj &&
hasProperty(obj, 'foo') &&
typeof obj.foo === 'string';
if (!isValid) {
throw new Error();
}
};
declare var obj: unknown;
foo(obj);
obj.foo // ok
你將不得不在這里給 TypeScript 一些幫助:
type fooObj = object & { foo: unknown };
const foo = (obj: unknown) => {
if (typeof obj === 'object' && obj) {
if ('foo' in obj && typeof (obj as fooObj).foo === 'string') {
return (obj as fooObj).foo;
}
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.