簡體   English   中英

功能中的打字稿泛型類型錯誤

[英]typescript generic type error in function

我將字符串類型放在泛型中,但似乎該值無法將其識別為字符串 任何人都請幫我解決代碼中的錯誤

謝謝!

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);
});

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

對象上的方法,如 toString、toLocaleString、valueOf、hasOwnProperty、isPrototypeOf 和 propertyIsEnumerable 將不再可用。

您可以將 {} 的顯式約束添加到類型參數以獲取舊行為。

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