简体   繁体   English

功能中的打字稿泛型类型错误

[英]typescript generic type error in function

I put the string type in the generic, but it seems that the value doesn't recognize it as a string Anyone please help me to resolve the error in the code我将字符串类型放在泛型中,但似乎该值无法将其识别为字符串 任何人都请帮我解决代码中的错误

thanks!谢谢!

interface DropDownItem<T> {
  value: T;
  selected: boolean;
}

const emails: DropDownItem<string>[] = [
  { value: 'naver.com', selected: true },
  { value: 'gmail.com', selected: false },
  { value: 'hanmail.com', selected: false },
];

function createDropdownItem<T>(item: DropDownItem<T>): HTMLOptionElement {
  const option = document.createElement('option');
  option.value = item.value.toString(); // Error: Type'T' does not have property'toString' ts(2339)
  option.innerText = item.value.toString(); // Error: Type'T' does not have property'toString' ts(2339)
  option.selected = item.selected;
  return option;
}

emails.forEach(function (email) {
  const item = createDropdownItem<string>(email);
  const selectTag = document.querySelector('#email-dropdown');
  selectTag?.appendChild(item);
});

Take a look at https://devblogs.microsoft.com/typescript/announcing-typescript-3-5/#generic-type-parameters-are-implicitly-constrained-to-unknown看看https://devblogs.microsoft.com/typescript/annoucing-typescript-3-5/#generic-type-parameters-are-implicitly-constrained-to-unknown

methods on Object like toString, toLocaleString, valueOf, hasOwnProperty, isPrototypeOf, and propertyIsEnumerable will no longer be available.对象上的方法,如 toString、toLocaleString、valueOf、hasOwnProperty、isPrototypeOf 和 propertyIsEnumerable 将不再可用。

you can add an explicit constraint of {} to a type parameter to get the old behavior.您可以将 {} 的显式约束添加到类型参数以获取旧行为。

function createDropdownItem<T extends {}>(item: DropDownItem<T>): HTMLOptionElement {
  const option = document.createElement('option');
  option.value = item.value.toString(); 
  option.innerText = item.value.toString();
  option.selected = item.selected;
  return option;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM