簡體   English   中英

如何根據Typescript中的字符串參數定義函數的參數類型?

[英]How to define a function's argument type dependent on string argument in Typescript?

我在 Javascript 代碼中有一個現有函數,我正在嘗試為其編寫類型定義文件以進行嚴格的類型檢查。 它是這樣使用的:

createElement("a", {href: "www.example.com"});

該項目使用自定義 html 元素。 第一個參數是一個帶有標簽的字符串,正如你所看到的,第二個參數的類型取決於字符串標簽,因為它應該是一個與標簽期望一致的屬性到值映射。

我正在嘗試這樣的事情,但它不起作用。

type Tag<T> = string;
const stringTag: Tag<string> = "IamString";
const numberTag: Tag<number> = "IamNumber";

function doStuff<T>(
    tag: Tag<T>,
    content: T
): void {
    console.log(tag, content);
}

doStuff(stringTag, "IshouldBeString");
doStuff(numberTag, "IshouldBeNumber"); // Should be WRONG
doStuff(numberTag, 10); // CORRECT

它會抱怨未使用的“T”參數,並且不會抱怨 numberTag 的字符串參數錯誤。 如果我使用現有的泛型類型,如Array<T>而不是Tag<T> , doStuff 會正確約束第二個參數。

我正在嘗試維護現有的 api(字符串類型標簽),但可以考慮更改它。

謝謝。

我能想到的唯一方法是“字符串文字類型”和條件類型,因此您必須手動拼出所有這些類型定義。

type TagType = "a" | "button";
type Tag<T extends TagType> =
    T extends "a" ? AType :
    T extends "button" ? ButtonType : never;

interface AType {
    href: string;
}

interface ButtonType {
    onClick: () => void
}

function doStuff<T extends TagType>(tag: T, content: Tag<T>) {
    console.log(tag, content)
}

doStuff("a", { href: "" }); // CORRECT
doStuff("button", { href: "" }); // WRONG
doStuff("button", { onClick: () => {} }); // CORRECT

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM