假设你有一个对象类型:
Type Person = {
name?: string;
color?: string;
address? string;
}
但是你想将该类型更改为以下类型,你知道名称和颜色将存在。
Type Person = {
name: string;
color: string;
address? string;
}
因此,有函数
const throwIfUndefined = (
object: {[key: string]: any},
requiredKeys: string[]
): ReturnTypeHere => {
for (const key of requiredKeys) {
if (!object[key]) throw new Error("missing required key");
}
return object;
};
键入函数参数和返回类型 (ReturnTypeHere
) 的正确方法是什么?正确编写,下面将 1) 抛出错误 2) 控制台记录名称。它永远不会控制台日志未定义。
const person = {...}
const requiredKeys = ["name", "color"];
const verifiedPerson = throwIfUndefined(person, requiredKeys);
console.log(verifiedPerson.name)
最佳答案
如果你有一个对象类型 T
及其键的联合 K
你想要的,你可以写RequireKeys<T, K>
像这样:
type RequireKeys<T extends object, K extends keyof T> =
Required<Pick<T, K>> & Omit<T, K>;
这里我们使用 Required<T>
, Pick<T, K>
, 和 Omit<T, K>
实用程序类型。这里可能存在极端情况,例如 T
。有一个字符串索引签名和 string
出现在里面K
,但初步估计应该可行。
理解什么也有点难RequiredKeys<Person, "name" | "color">
来自它在您的 IDE 中的显示方式:
type VerifiedPerson = RequireKeys<Person, "name" | "color">;
// type VerifiedPerson = Required<Pick<Person, "name" | "color">> &
// Omit<Person, "name" | "color">
如果你想让编译器更明确一点,你可以对expand做类似下面的事情。类型到它的属性中:
type RequireKeys<T extends object, K extends keyof T> =
(Required<Pick<T, K>> & Omit<T, K>) extends
infer O ? { [P in keyof O]: O[P] } : never;
结果
/* type VerifiedPerson = {
name: string;
color: string;
address?: string | undefined;
} */
哪个更容易看。
--
然后你需要制作throwIfUndefined()
一个generic function所以编译器可以跟踪 object
之间的关系和 requiredKeys
传入:
const throwIfUndefined = <T extends object, K extends keyof T>(
object: T,
requiredKeys: readonly K[]
) => {
for (const key of requiredKeys) {
if (!object[key]) throw new Error("missing required key");
}
return object as unknown as RequireKeys<T, K> // need to assert this
};
并测试:
const person: Person = {
...Math.random() < 0.8 ? { name: "Alice" } : {},
...Math.random() < 0.8 ? { color: "Color for a person is problematic" } : {}
};
const requiredKeys = ["name", "color"] as const;
const verifiedPerson = throwIfUndefined(person,
requiredKeys); // possible runtime error here
// const verifiedPerson: RequireKeys<Person, "name" | "color">
如果你想让编译器记住 literal types "name"
和 "color"
是 requiredKeys
的成员那么你需要做类似 const
assertion 的事情(即 as const
)这样说。否则requiredKeys
只是string[]
并且你会得到奇怪/错误的结果(我们可以防止这些,但它可能超出这里的范围)。
现在,编译器理解 name
和 color
被定义,而 address
仍然是可选的:
console.log(verifiedPerson.name.toUpperCase() + ": " +
verifiedPerson.color.toUpperCase()); // no compile error
// [LOG]: "ALICE: COLOR FOR A PERSON IS PROBLEMATIC"
verifiedPerson.address // (property) address?: string | undefined
关于javascript - Typescript typecast object 所以特定的必需键在类型中不再是可选的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66679911/