我有一个关于接口的 typescript 可选属性的问题。假设以下代码:
interface Test {
prop1: string;
prop2?: string;
}
function someFunction(data: {prop1: string, prop2: string}) {
console.log(data.prop1 + ": " + data.prop2);
}
function otherFunction(data: Test) {
if (data.prop2) {
someFunction(data); // prop2 might be undefined!
}
}
Run Code Online (Sandbox Code Playgroud)
并将严格模式设置为 true。
打字稿给了我以下错误:
Argument of type 'Test' is not assignable to parameter of type '{ prop1: string; prop2: string; }'.
Property 'prop2' is optional in type 'Test' but required in type '{ prop1: string; prop2: string; }'.
Run Code Online (Sandbox Code Playgroud)
问题是:为什么会这样?如果断言,为什么打字稿不理解这一点?
首先,我很想了解为什么?但如果可能的话,还有一些不产生任何额外运行时代码或大量类型断言的解决方法会很好吗?
我正在尝试编写一个用户定义的类型保护来测试给定的值是否具有给定数组中的所有属性。
我调用这个函数hasAll,它在 Javascript 中的实现和用法如下所示:
function hasAll(obj, keysToCheck) {
if (!obj) return false;
for (const key of keysToCheck) {
const value = obj[key];
if (value === null) return false;
if (value === undefined) return false;
}
return true;
}
hasAll({ foo: 'test', bar: 5 }, ['foo', 'bar']); // true
hasAll({ foo: 'test', bar: 5 }, ['foo', 'bar', 'baz']); // false
Run Code Online (Sandbox Code Playgroud)
我现在想做的是将上面的函数变成类型保护。这是我到目前为止所拥有的:
// this _almost_ works
type Nullable<T> = T | null | undefined;
type RemoveNullables<T, …Run Code Online (Sandbox Code Playgroud)