Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

typescript - Constraining shape of static dictionary while retaining type inference for it's exact shape

Let's say I have a static dictionary:

const myDict = {
  1: "one",
  2: "two",
}

TypeScript now infers that typeof myDict to exactly match the shape myDict, which is very nice, because IDE can autocomplete myDict keys for me

I would now like to constrain the dictionary so it must conform to the pattern { [k: number]?: string }, but retaining the exact type inference, so I don't lose autocomplete. When I type it explicitly:

const myDict: { [k: number]?: string } = {
  1: "one",
  2: "two",
}

then typeof myDict changes from { 1: "one", 2: "two" } to { [k: number]?: string }, ruining my autocomplete. Is here a straight-forward way to do this?

question from:https://stackoverflow.com/questions/65541107/constraining-shape-of-static-dictionary-while-retaining-type-inference-for-its

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...