TypeScript FAQ All In One
TypeScript FAQ All In One
generic demo bug
interface Named<T> {
name: string;
value: T; // <-- added
}
class MyNamed<T> implements Named<T> {
// name: 'mine'|undefined;
// name!: 'mine';
// name: 'mine'="mine";
name: string = 'mine';
// value: T;
value!: T; // <-- added
}
function findByName<T>(x: Named<T>): T {
// TODO: Implement
return undefined;
// ❌
// Type 'undefined' is not assignable to type 'T'.
// 'T' could be instantiated with an arbitrary type which could be unrelated to 'undefined'.(2322)
}
var x: MyNamed<string> = {
name: 'eric',
value: '2022',
};
var y = findByName(x); // got y: string;
https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#generics
refs
https://www.cnblogs.com/xgqfrms/p/12453976.html
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16084831.html
未经授权禁止转载,违者必究!