我为我的应用程序创建了一个滤镜功能.我需要的一件事是一个更新函数,用于根据id更改选定过滤器的值.下面是我正在做的一个非常简单的例子:
interface DictionaryItem<Type> {
value: Type;
stringify: (value: Type) => string | null;
}
interface Dictionary {
age: DictionaryItem<number>;
isNice: DictionaryItem<boolean>;
nickname: DictionaryItem<string>;
}
const items: Dictionary = {
age: {
value: 44,
stringify: value => String(value),
},
isNice: {
value: true,
stringify: value => value ? "yes" : null,
},
nickname: {
value: "Joey",
stringify: value => value,
},
};
type UpdateFunction = <Type extends keyof Dictionary>(id: Type, value: Dictionary[Type]["value"]) => void;
const update: UpdateFunction = (id, value) => {
items[id].value = value;
// Here's the problem - TypeScript thinks that
// stringify signature is stringify(never)
const stringified = items[id].stringify(value);
console.log(stringified);
};
update("age", 45);
问题是我不能调用items[id].stringify(value);
,因为在本例中,TypeScrip将stringify
方法解析为stringify(value: never)
.
我如何才能让TypeScrip理解我的update()
函数中预期的stringify()
类型?这never
人是从哪里来的呢?