gpt4 book ai didi

typescript - 在条件类型中使用值而不是类型

转载 作者:行者123 更新时间:2023-12-05 05:32:15 27 4
gpt4 key购买 nike

<分区>

我想要一个时间类型 (00:00),它是一个只允许有效时间的字符串。考虑这个 Time 类型按我喜欢的方式工作:

const hours = [
'00' , '01', '02', '03', '04', '05', '06', '07', '08',
'09' , '10', '11', '12', '13', '14', '15', '16',
'17' , '18', '19', '20', '21', '22', '23', '24'
] as const

type HH = typeof hours[number]

const minutes = [
'00', '01', '02', '03', '04', '05', '06', '07', '08', '09',
'10', '11', '12', '13', '14', '15', '16', '17', '18', '19',
'20', '21', '22', '23', '24', '25', '26', '27', '28', '29',
'30', '31', '32', '33', '34', '35', '36', '37', '38', '39',
'40', '41', '42', '43', '44', '45', '46', '47', '48', '49',
'50', '51', '52', '53', '54', '55', '56', '57', '58', '59'
] as const

type MM = typeof minutes[number]

type Time = `${HH}:${MM}`

编写这种类型的一种更简洁的方法是:

const digits = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ] as const
type Digit = typeof digits[number]
type HH1 = `${Digit}${Digit}` // can be 99, needs to be < 24!
type MM1 = `${Digit}${Digit}` // can be 99, needs to be < 60!
type Time1 = `${HH1}:${MM1}$` // can be 99:99, needs to be max 24:59

所以我尝试使用typeof digits[number]类型的number数组索引值或者输出string值来实现小时 < 24 分钟 < 60。我可以使用 number 值而不是类型或 string 值在条件类型中实现此目的吗?

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com