我有一个使用keyof特性的简单函数:
interface B {
name: string;
age: number;
}
function test(key: keyof B) {}
const c = {
age: 'age'
}
test(c.age);上面代码的问题是typescript抛出了一个错误,即type string is not assignable to keyof B。
那么,如果keyof特性不能与对象键值一起使用,那么它还有什么意义呢?我不想添加as keyof B。
发布于 2019-02-27 22:37:39
问题是typescript不能在默认情况下推断对象属性的文字类型(即使它们是const)。
您可以通过对string文本类型使用类型断言来解决此问题:
const c = {
age: 'age' as 'age'
}
test(c.age);或者你想为一个对象的所有属性推断字符串类型,你可以使用一个函数(我在这里使用了一个iffe,但它可以是一个单独的函数)
const c = (<V extends string, T extends Record<string, V>>(o: T) => o)({
age: 'age'
});
test(c.age);或者在3.4 (尚未发布)中,您可以在对象上使用as const断言:
const c = {
age: 'age'
} as const
test(c.age);发布于 2019-02-27 22:35:16
由于隐式类型,c.age将是一个字符串(c将是{age:string}类型)。您可以将c.age的类型定义为keyof B。这还会限制您将其他值分配给age属性并意外地使用它们。
interface B {
name: string;
age: number;
}
function test(key: keyof B) { }
const c: { age: keyof B } = {
age: 'age'
}
test(c.age);发布于 2019-02-27 22:37:42
原因是TypeScript推断c的类型是{age: string;},而不是{age: 'age';}。
如果它推断是后者,而不是前者,你就不能像这样改变c.age:
const c = { age: 'age' }
c.age = 'somethingElse';如果您直接使用文字'age'调用它,它就会像广告中所说的那样工作。
您可以使用适当的类型覆盖TypeScript推断,如下所示:
const c: {age: 'age'} = {
age: 'age',
};这将使类型错误消失,并强制除了文字字符串'age'之外不将任何内容赋给c.age。
https://stackoverflow.com/questions/54907763
复制相似问题