【发布时间】:2018-04-04 04:44:32
【问题描述】:
我正在尝试构建一个类型安全的附件系统,但是当泛型函数调用中的类型不匹配时,打字稿似乎不会引发错误
// Generic key that holds value type info
type GenericTypeMarker<T> = string;
// Standard dictionarny
const dictionary: { [id: string]: any } = {};
// Put item into dict with type specified by key
function putItem<T>(key: GenericTypeMarker<T>, item: T) {
dictionary[key] = item;
}
// Get item from dict with type specified by key
function getItem<T>(key: GenericTypeMarker<T>): T {
return dictionary[key];
}
// A test key with type of number
const TestKey: GenericTypeMarker<number> = "testKey";
// type mismatch between value and key, but no error
putItem(TestKey, "not a string");
我不明白为什么当键和值的类型不对齐时最后一行不会引发编译器错误。
编辑:根据 jcalz 的评论,我理解为什么会这样。但是,有没有一种方法可以保持类型安全?
【问题讨论】:
标签: typescript generics