我試圖const通過傳入一個我想用作型別的字串來生成一個型別化的物件,這可能嗎,我已經嘗試了下面的方法并且它帶出了錯誤的型別。
const test = <T> (name: T) => {
const hi: { name: T } = {
name
} as const
return hi
}
const test1 = test('hello')
我希望這是型別
{
name: 'hello';
}
但相反,它是型別
{
name: string;
}
uj5u.com熱心網友回復:
為了推斷引數的文字型別,通常需要為泛型引數添加適當的約束。看這個例子:
function test<T extends string>(name: T) {
return { name };
}
const test1 = test('hello') // {name:"hello"}
如果您對更多示例感興趣,可以查看我的文章
如果要添加一些驗證,可以使用條件型別:
type IsHello<T extends string> = T extends 'hello' ? T : never
function test<T extends string>(name: IsHello<T>) {
return { name };
}
const test1 = test('hello') // {name:"hello"}
const test2 = test('not a hello') // expected error
或者您可以使用此實用程式型別:
type IsLiteral<T extends string> = T extends string ? string extends T ? never : T : never
function test<T extends string>(name: IsLiteral<T>) {
return { name };
}
如果您只想允許字串文字
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/410839.html
標籤:
