[英]Typescript: type safety for interface properties in a function declaration
假设我们有这个简单的例子:
interface Steps {
stepOne?: boolean;
stepTwo?: boolean;
stepThree?: boolean;
}
let steps: Steps = {};
function markStepDone (step: ???) {
steps[step] = true;
}
markStepDone('anything');
如何防止它允许将“任何”传递给此函数并仅允许['stepOne','stepTwo','stepThree']?
我也尝试用枚举来做,但事实证明你不能使用枚举作为索引签名...
你正在寻找的是keyof
运算符,它正在本周实现(是的,真的)。 它准备好后会看起来像这样:
function markStepDone (step: keyof Steps) {
steps[step] = true;
}
这里有一个名字不同的早期PR(keysof): https : //github.com/Microsoft/TypeScript/pull/10425
同时, string
是粗略的近似值,或者是手写类型"stepOne" | "stepTwo" | "stepThree"
"stepOne" | "stepTwo" | "stepThree"
"stepOne" | "stepTwo" | "stepThree"
将为您提供keyof Steps
的确切行为
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.